So im trying to invoke my toString method in my AccountWithException class to print the user input contained in the file as well, but for some reason i cant crack as to why it wont print. I tried to do System.out.println(pw.toString())..only to get the memory location constantly being printed to me. Initially i was just reading the file back in however my instructor specified this: "Use the overloaded toString method to output to the console and file (via PrintWriter)" I used the overloaded toString for my object but cant figure it out for my file. Is there something ive overlooked in my code or is this a simple Sysout.println() statement? Requirements have been added.
1.) Prompt user for an output filename. Create a file for text output.
2.) If file exists prompt user for a new filename. Do not continue until a valid, non existing filename is entered and file is opened for output.
3.) Prompt user for first name, last name, balance, (account id and annual interest rate can be constants)
4.) Create AccountWithExceptionObject that includes the user specified data.
5.) If valid data in the object exists: output the object information to the display AS WELL AS the opened output file. USE the overloaded toString() method when outputting the data. If invalid data exists (< 0) then throw your custom InvalidBalanceException.
6.) Use finally block to ensure output file has been properly closes.
import java.util.Scanner;
import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.IOException;
import java.io.PrintWriter;
//import java.io.FileReader;
//import java.io.BufferedReader;
public class TestAccountWithException {
public static void main(String[] args) throws InvalidBalanceException, FileNotFoundException, IOException {
// variable declaration
String fileName;
String firstName;
String lastName;
double balance;
int id = 1122;
final double RATE = 4.50;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a file name: ");
fileName = input.next();
File fw = new File(fileName + ".txt");
// while loop to check if file already exists
while (fw.exists()) {
System.out.print("File already exists, enter valid file name: ");
fileName = input.next();
fw = new File(fileName + ".txt");
}
System.out.print("Enter your first name: ");
firstName = input.next();
System.out.print("Enter your last name: ");
lastName = input.next();
// concatanate full/last name
String fullName = firstName.concat(" " + lastName);
System.out.print("Input beginnning balance: ");
balance = input.nextDouble();
PrintWriter pw = null;
// pass object to printwriter and pw to write to the file
pw = new PrintWriter(fw);
// print to created file
pw.println(firstName);
pw.println(lastName);
pw.println(balance);
pw.println(id);
pw.println(RATE);
String line = null;
try {
// pass user input to object
AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);
System.out.println(acctException.toString());
// create the object
//FileReader fr = new FileReader(fileName + ".txt");
// pass to buffered reader and use its preset commands for alteration to file
//BufferedReader br = new BufferedReader(fr);
//System.out.println("Text file opened and reading...");
// read in lines from file
// while ((line = br.readLine()) != null) {
//System.out.println(line);
//}
// close buffered reader
//br.close();
// custom exception if balance < 0
} catch (InvalidBalanceException e) {
System.out.println(e.getMessage());
//} catch (FileNotFoundException e) {
//System.out.println("File not found" + fileName);
//} catch (IOException e) {
//System.out.println(e.getMessage());
} finally {
System.out.println("Text file closing...");
pw.close();
}
} // end main
} // end class
public class AccountWithException {
private int id;
private double balance;
private static double annualInterestRate;
private java.util.Date dateCreated;
// CRE additions for lab assignment
private String name;
// no-arg constructor to create default account
public AccountWithException() {
this.dateCreated = new java.util.Date();
}
//constructor for test account with exception that takes in arguments
public AccountWithException(String newName, double newBalance, int newId, double newRate) throws InvalidBalanceException {
setName(newName);
setBalance(newBalance);
setId(newId);
setAnnualInterestRate(newRate);
this.dateCreated = new java.util.Date();
}
/* // constructor for test account with exception that takes in arguments
public AccountWithException(String newName, double newBalance, int newId, double newRate) {
this.name = newName;
this.balance = newBalance;
this.id = newId;
AccountWithException.annualInterestRate = newRate;
this.dateCreated = new java.util.Date();
} */
// accessor methods
public int getId() {
return this.id;
}
public double getBalance() {
return this.balance;
}
public static double getAnnualInterestRate() {
return annualInterestRate;
}
public double getMonthlyInterest() {
return this.balance * (this.annualInterestRate / 1200);
}
public java.util.Date getDateCreated() {
return this.dateCreated;
}
public String getName() {
return this.name;
}
// mutator methods
public void setId(int newId) {
this.id = newId;
}
public void setBalance(double newBalance) throws InvalidBalanceException {
if(newBalance >= 0) {
this.balance = newBalance;
}
else {
throw new InvalidBalanceException(newBalance);
}
}
public static void setAnnualInterestRate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}
public void setName(String newName) {
this.name = newName;
}
// balance modification methods
public void withdraw(double amount) {
this.balance -= amount;
}
public void deposit(double amount) {
this.balance += amount;
}
// override of Object method
public String toString() {
// return string with formatted data
// left-align 20 character column and right-align 15 character column
return String.format("%-20s%15d\n%-20s%15tD\n%-20s%15s\n%-20s%15.2f%%\n%-20s%,15.2f\n",
"ID:", this.id,
"Created:", this.dateCreated,
"Owner:", this.name,
"Annual Rate:", this.annualInterestRate,
"Balance:", this.balance);
}
}
public class InvalidBalanceException extends Exception {
private double balance;
public InvalidBalanceException(double balance) {
// exceptions constructor can take a string as a message
super("Invalid Balance " + balance);
this.balance = balance;
}
public double getBalance() {
return balance;
}
}
Try to slap an #Override on your tostring method.
// override of Object method
#Override
public String toString() {
// return string with formatted data
// left-align 20 character column and right-align 15 character column
return String.format("%-20s%15d\n%-20s%15tD\n%-20s%15s\n%-20s%15.2f%%\n%-20s%,15.2f\n",
"ID:", this.id,
"Created:", this.dateCreated,
"Owner:", this.name,
"Annual Rate:", this.annualInterestRate,
"Balance:", this.balance);
}
}
Also, when naming your classes, you shouldn't put "WithException" on them if they throw an exception. This class should simply be "Account".
Related
I am extremely stuck on this assignment I have, this is the last part of the assignment and it is going over my head. We were given this code to start off with.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
Employee e1 = new Employee2(7, "George Costanza");
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e1.displayEmployee();
//Employee e2 = createEmployeeFromFile();
//e2.displayEmployee();
}
}
We were told to create a method called createEmployeeFromFile();. In this method we are to read from a .txt file with a Scanner and use the data to create an Employee object. Now I am confused on two things. First on the method type I should be using, and how to create an object with the data from the .txt file. This is the first time we have done this and it is difficult for me. Employee1 works fine, but when trying to create my method I get stuck on what to create it as.
Here is my rough draft code for right now.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
EckEmployee2 e1 = new EckEmployee2(7, "George Costanza");
EckEmployee2 e2 = createEmployeeFromFile();
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e2.setNumber();
e2.setName();
e2.setDepartment();
e2.setPosition();
e2.setSalary();
e2.setRank();
e1.displayEmployee();
e2.displayEmployee();
}
createEmployeeFromFile(){
File myFile = new File("employee1.txt");
Scanner kb = new Scanner(myFile);
}
}
I am not expecting to get the answer just someone to point me in the right direction. Any help is greatly appreciated.
Here is my code from my main class.
public class EckEmployee2 {
private int rank;
private double number;
private double salary;
private String name;
private String department;
private String position;
public EckEmployee2() {
number = 0;
name = null;
department = null;
position = null;
salary = 0;
rank = 0;
}
public EckEmployee2(double number, String name) {
this.number = number;
this.name = name;
}
public EckEmployee2(double number, String name, String department, String position, double salary, int rank) {
this.number = number;
this.name = name;
this.department = department;
this.position = position;
this.salary = salary;
this.rank = rank;
}
public void setNumber(double num) {
this.number = num;
}
public double getNumber() {
return this.number;
}
public void setName(String nam) {
this.name = nam;
}
public String getName() {
return this.name;
}
public void setDepartment(String dept) {
this.department = dept;
}
public String getDepartment() {
return this.department;
}
public void setPosition(String pos) {
this.position = pos;
}
public String getPosition() {
return this.position;
}
public void setSalary(double sal) {
this.salary = sal;
}
public double getSalary() {
return this.salary;
}
public void setRank(int ran) {
this.rank = ran;
}
public int getRank() {
return this.rank;
}
public boolean checkBonus() {
boolean bonus = false;
if (rank < 5) {
bonus = false;
} else if (rank >= 5)
bonus = true;
return bonus;
}
public void displayEmployee() {
if (checkBonus() == true) {
System.out.println("-------------------------- ");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: \n" + department);
System.out.println("Position: \n" + position);
System.out.printf("Salary: %,.2\n" , salary);
System.out.println("Rank: \n" + rank);
System.out.printf("Bonus: $\n", 1000);
System.out.println("-------------------------- ");
} else if (checkBonus() == false)
System.out.println("--------------------------");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: " + department);
System.out.println("Position: " + position);
System.out.printf("Salary: %,.2f\n" , salary);
System.out.println("Rank: " + rank);
System.out.println("-------------------------- ");
}
}
To make things more clear here are the directions
Create a method in TestEmployee2 called createEmployeeFromFile() that will read data from a file and create, populate and return an Employee object. The file it will read from is called employee1.txt, which is provided. Hard code the name of the file in the method. This file contains the employee’s number, name, department, position, salary and rank. Create a Scanner object and use the Scanner class’s methods to read the data in the file and use this data to create the Employee object. Finally return the employee object.
In java, to return a value from a method, you add that objects type into the method signature as below, and in short java method signatures are as follows
'modifier (public, private, protected)' 'return type (void/nothing, int, long, Object, etc...' 'methodName(name the method)' 'parameters (any object or primitive as a parameter'
The method below will work if you have an employee contstructor which parses the input text, and assuming the data is split my a delimiter, you can use String.split(splitString); where splitString is the character that splits the data, i.e) a comma ",".
public EckEmployee2 getEmployee()
{
try
{
/**
* This will print where your java working directory is, when you run the file
*
*/
System.out.println(System.getProperty("user.dir"));
/**
* Gets the file
*/
File myFile = new File("employee1.txt");
/**
* Makes the scanner
*/
Scanner kb = new Scanner(myFile);
/**
* A list to store the data of the file into
*/
List<String> lines = new ArrayList<>();
/**
* Adds all the lines in the file to the list "lines"
*/
while (kb.hasNext())
{
lines.add(kb.next());
}
/**
* Now that you have the data from the file, assuming its one line here, you can parse the data to make
* your "Employee"
*/
if (lines.size() > 0)
{
final String line = lines.get(0);
return new EckEmployee2(line);
}
}
/**
* This is thrown if the file you are looking for is not found, it either doesn't exist or you are searching
* in the wrong directory.
*/
catch (FileNotFoundException e)
{
e.printStackTrace();
}
/**
* Return null if an exception is thrown or the file is empty
*/
return null;
}
First your method createEmployeeFromFile() must take 2 parameters, a Scanner object to read input, and the File you're gonna be reading from using the Scanner.
The return type is Empolyee2 because the method creates a Employee2 instance and must return it.
Now, I gave you the initiatives.
Your turn to read more about Scanner object and File object.
Reading from the text file, the attributes of your object, is easy then you create an instance by using the constructor with the attributes and return it!
Hope this helps.
I need help creating a method that loads pets. I am having difficulty
writing a while loop that reads the file pets.txt and stores it in an array
list and returns the total number of pets. Once I have the pets loaded I
need to create a method to print the list, a method to find the heaviest
pet and a method to find the average weight of the pets.
Here is what I have so far:
try {
inFile = new Scanner(new FileReader("pets.txt"));
} catch (FileNotFoundException ex) {
System.out.println("File data.txt not found");
System.exit(1);
}
int i = 0;
while (inFile.hasNext() && i < list.length) {
// cant figure out how to write this
i++;
}
inFile.close();
return i;
pets.txt looks like this:
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
The format of this information is
(name of pet, name of owner, weight, breed)
Solution
This is my solution to this problem with the methods that you mentioned that you wanted. I simply just create a pet class and create an arraylist of the pet object and add the pet objects to the list when I use the scanner to get the data from the file!
Pet Class
public class Pet {
//Fields Variables
private String pet_name;
private String owner_name;
private double weight;
private String breed;
//Constructor
public Pet (String name, String o_name, double weight, String breed) {
//Set the variable values
this.pet_name = name;
this.owner_name = o_name;
this.weight = weight;
this.breed = breed;
}
//Getter and setter
public String getPet_name() {
return pet_name;
}
public void setPet_name(String pet_name) {
this.pet_name = pet_name;
}
public String getOwner_name() {
return owner_name;
}
public void setOwner_name(String owner_name) {
this.owner_name = owner_name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
Main Class
public class Main {
//ArrayList
private static ArrayList<Pet> pets = new ArrayList<>();
public static void main (String [] args) {
try {
Scanner sc = new Scanner(new File("path/to/file.txt")).useDelimiter(", |\n");
while (sc.hasNext()) {
//Get the info for the pet
Pet pet;
String name = sc.next();
String owner_name = sc.next();
double weight = sc.nextDouble();
String breed = sc.next();
//Create the pet and add it to the array list
pet = new Pet (name, owner_name, weight, breed);
pets.add(pet);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Add your custom pets here if you would like!
addNewPet ("muffy", "john", 30.0, "beagle");
//Custom Methods
printList();
findHeaviestPet();
findLightestPet();
getAveragePetWeight();
}
public static void printList () {
for (int i = 0; i < pets.size(); i++) {
System.out.println (pets.get(i).getPet_name()+" "+pets.get(i).getOwner_name()
+" "+pets.get(i).getWeight()+" "+pets.get(i).getBreed());
}
}
public static void findLightestPet () {
//So we know the value will be assigned on the first pet
double weight = Double.MAX_VALUE;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() < weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The lightest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void findHeaviestPet () {
double weight = 0.0;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() > weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The heaviest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void getAveragePetWeight() {
double weights = 0;
for (int i = 0; i < pets.size(); i++) {
weights += pets.get(i).getWeight();
}
weights = (weights / pets.size());
System.out.println ("The average weight is "+weights);
}
public static void addNewPet (String name, String o_name, double weight, String breed) {
Pet pet = new Pet(name, o_name, weight, breed);
pets.add(pet);
}
}
Pets.txt
Please make sure that between every item there is a command and space like this ", " that is so we know when the next item is.
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
name, owner_name, 65.0, breed
In your loop you iterate over every line of the file. So you have to parse the line in it´s content (Split) and then save the informations in
Second you should create an Pet-Object (Objects and Classes) and save the information in each object. Your arraylist contains the created objects.
If you got some specific code, maybe someone will give you a more specific help.
What you have done so far is too "load" the file. You must now use the inFile (the scanner object) to access the contents of the pets.txt. This can be done in many ways such as using inFile.nextLine() (see the Javadocs).
Thereafter use string methods such as split() (again see the docs) to extract whichever parts of the string you want in the necessary format, to store in a Pets class.
You should then store each Pets object in a data structure (e.g. list) to enable you to write the methods you need in an efficient manner.
Pet Class
Public class Pet {
Public Pet(String pet_name, String owner, float weight, String breed) {
this.pet_name = pet_name;
this.owner = owner;
this.weight = weight;
this.breed = breed;
}
String pet_name;
String owner;
float weight;
String breed;
//implements getters and setters here
}
File reading method
private void read_file() throws Exception {
Scanner scanner = new Scanner(new FileReader("filename.txt"));
List<Pet> list = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] data = scanner.nextLine().split(",");
Pet pet = new Pet(data[0], data[1], Float.valueOf(data[2]), data[3]);
list.add(pet);
}
}
First of all I would not read the data into a simple array list. I would probably use an ArrayList of classes. So I would declare a second class something like this:
//Declare pet class
class Pet{
// Can be either public or private depending on your needs.
public String petName;
public String ownerName;
public double weight;
public String breed;
//Construct new pet object
Pet(String name, String owner, double theWeight, String theBreed){
petName = name;
ownerName = owner;
weight = theWeight;
breed = theBreed;
}
}
Then back in whatever your main class is I would make the following method:
public ArrayList<Pet> loadFile(String filePath){
ArrayList<Pet> pets = new ArrayList<Pet>();
File file = new File(filePath);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String s[] = sc.nextLine().split(",");
// Construct pet object making sure to convert weight to double.
Pet p = new Pet(s[0],s[1],Double.parseDouble(s[2]),s[3]);
pets.add(p);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return pets;
}
I have been working at this for about 20 hours to resolve this issue and I have come to the conclusion that I need to ask you fine people for help! I'm very new to Java and am just learning to use other classes in addition to main. I am supposed to
Get the customer name via user keyboard input in the main class.
Next, I am supposed to use the customer name to open its file in
the Customer class which uses a scanner to get their name,
address, initial acct balance and the name of their corresponding
transaction file.
Now, in the Transaction class I am supposed
to call in the transactionFileName (a String) as a parameter for the
(Transaction class) Constructor which is used to open the Scanner
for the customer's transactionFile.
Finally, I need to Load the
transactions from the transactionFile in a method (with no
parameters and a void return type). I keep getting a
FileNotFoundException "Result too large runtime error" when I call
aCustomer.LoadTransaction() in main.
The error tells me it is occurring at the LoadTransaction() line in the Transaction class... Here is the error:
run:
Enter the customer's LAST name you wish to look up:
Tolliver
TOLLIVER.txt
5369.0
Exception in thread "main" java.io.FileNotFoundException: (Result too large)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at jslab10.Transaction.LoadTransaction(Transaction.java:23)
at jslab10.JSLAB10.main(JSLAB10.java:31)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
Here is the code for Main, Customer, and the Transaction classes. Any help or guidance would be very much appreciated!
This is the code for the Main class in package Lab10JS:
package jslab10;
import java.io.*;
import java.util.Scanner;
public class JSLAB10 {
public static void main(String[] args) throws IOException {
Transaction aTransaction;
Customer aCustomer;
String aCustomerFileName;
aCustomerFileName = GetFileName();
aCustomer = new Customer(aCustomerFileName);
aTransaction = new Transaction();
System.out.println(aCustomer.GetBalance());
String transactionFileName = aCustomer.GetTransactionFileName();
aTransaction = new Transaction(transactionFileName);
aTransaction.LoadTransaction();
System.out.println(aTransaction.GetDate());
}
public static String GetFileName() {
String aCustomerFileName;
String custInput;
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the customer's LAST name you "
+ "wish to look up: ");
custInput = kbd.nextLine();
aCustomerFileName = custInput.toUpperCase() + ".txt";
System.out.println(aCustomerFileName);
return aCustomerFileName;
}
}
This is the code for Customer class in Lab10JS package:
package jslab10;
import java.util.Scanner;
import java.io.*;
public class Customer {
private String name;
private String streetAddress;
private String cityStateZip;
private double balance;
public static String transactionFileName;
private String customerFileName;
public Customer(String aCustomerFileName) throws IOException {
try (Scanner inFileSC = new Scanner(new File(aCustomerFileName))) {
name = inFileSC.nextLine();
streetAddress = inFileSC.nextLine();
cityStateZip = inFileSC.nextLine();
balance = Double.parseDouble(inFileSC.nextLine());
inFileSC.nextLine();
transactionFileName = inFileSC.nextLine();
inFileSC.nextLine();
inFileSC.close();
}
}
public Customer() throws IOException {
}
public String GetTransactionFileName() {
return transactionFileName;
}
public double GetBalance() {
return balance;
}
/*
private void UpdateBalance(Transaction aTransaction) {
aTransaction.GetAmount();
aTransaction.GetTransactionCode();
while(aTransaction.GetTransactionCode() == 'C' ||
aTransaction.GetTransactionCode() == 'W' ||
aTransaction.GetTransactionCode() == 'T') {
}
}
*/
}
Here is the code for the Transaction class in package Lab10JS:
package jslab10;
import java.io.*;
import java.util.Scanner;
public class Transaction {
private String date;
private String description;
private double amount;
private char transactionCode;
private Scanner transactionFile;
public Transaction() {
}
public Transaction(String transactionFileName) throws IOException {
transactionFile = new Scanner(new File(transactionFileName));
}
public void LoadTransaction() {
date = transactionFile.nextLine();
description = transactionFile.nextLine();
amount = Double.parseDouble(transactionFile.nextLine());
transactionFile.nextLine();
transactionCode = transactionFile.nextLine().charAt(0);
}
public String GetDate() {
return date;
}
public String GetDescription() {
return description;
}
public double GetAmount(){
return amount;
}
public char GetTransactionCode() {
return transactionCode;
}
public boolean TestMoreTransactions() {
boolean result = false;
while(transactionFile.hasNext()) {
result = true;
}
return result;
}
}
So I had to design a class that read in stock symbol,name,previous closing price and current price. I then made this driver to instantiate different arrays to do different things with it. I had trouble reading the data as a file. The file has strings and numbers so I decided to read all the data as strings and then parse the ones I needed into doubles. I believe the error occurs when I am reading from the file. I am getting this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "AAPL"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at StockDriver.setStockData(StockDriver.java:31)
at StockDriver.main(StockDriver.java:10)
Any help would be appreciated. Here is my StockDriver code:
import java.text.DecimalFormat;
import java.io.*;
import java.util.Scanner;
import java.io.IOException;
public class StockDriver {
public static void main(String [] args) throws IOException{
Stock [] myStock = new Stock[10];
setStockData(myStock);
displayStockData(myStock);
} //end main
public static void setStockData(Stock [] myStock) throws IOException {
File infile = new File("stockData.txt");
if(!infile.exists()){
System.out.println("No file");
System.exit(0);
}
Scanner scan = new Scanner(infile);
String symbol, name, previousClosingPriceString, currentPriceString;
double previousClosingPrice, currentPrice;
int i = 0;
while(scan.hasNext() && i < myStock.length){
symbol = scan.nextLine();
name = scan.nextLine();
previousClosingPriceString = scan.nextLine();
previousClosingPrice = Double.parseDouble(previousClosingPriceString);
currentPriceString = scan.nextLine();
currentPrice = Double.parseDouble(currentPriceString);
myStock[i] = new Stock(symbol, name, previousClosingPrice, currentPrice);
i++;
} //end while
} //end setStockData
public static void displayStockData(Stock [] myStock) {
DecimalFormat formatter = new DecimalFormat("#.00");
for(int i = 0; i < myStock.length; i++){
System.out.println(myStock[i]);
System.out.println("---------------");
}//end for
} //end displayStockData
} //end class
Here is my stock class code:
import java.text.DecimalFormat;
public class Stock{
private String symbol;
private String name;
private double previousClosingPrice;
private double currentPrice;
public Stock(){
symbol = "";
name = "";
previousClosingPrice = 0.0;
currentPrice = 0.0;
}//end default constructor
public Stock(String symbol, String name, double previousClosingPrice, double currentPrice){
this.symbol = symbol;
this.name = name;
this.previousClosingPrice = previousClosingPrice;
this.currentPrice = currentPrice;
}//end overloaded constructor
public void setSymbol(String symbol){
this.symbol = symbol;
}
public void setName(String name){
this.name = name;
}
public void setPreviousClosingPrice(double previousClosingPrice){
this.previousClosingPrice = previousClosingPrice;
}
public void setCurrentPrice(double currentPrice){
this.currentPrice = currentPrice;
}
public String getSymbol(){
return symbol;
}
public String getName(){
return name;
}
public double getPreviousClosingPrice(){
return previousClosingPrice;
}
public double getCurrentPrice(){
return currentPrice;
}
public void getChangePercent(double percentage){
double changePercent;
changePercent = previousClosingPrice - (currentPrice/100);
} //end getChangePercent()
public boolean equals(Stock anyStock){
if (this.name.equals(anyStock.getName()) && this.currentPrice == anyStock.getCurrentPrice() &&
this.symbol.equals(anyStock.getSymbol()) &&
this.previousClosingPrice == anyStock.getPreviousClosingPrice()&&
this.currentPrice == anyStock.getCurrentPrice())
return true;
else
return false;
} //end equals()
public String toString() {
String str = "";
str += "Stock Symbol : " + symbol;
str += "\nStock name : " + name;
str += "\nPrevious Price : " + previousClosingPrice;
str += "\nCurrent Price : " + currentPrice;
return str;
} //end toString
}//end class
And here is my text that I am reading in:
GPRO
GoPro, Inc.
89.93
89.8773
SBUX
Starbucks
75.26
75.76
JCP
JC Penney
8.18
7.72
AMZN
Amazon
323.71
319.94
AE
Adams Resources and Energy
44.71
44.69
CEP
Constellation Energy Partners
3.38
3.35
KO
Coca-Cola
43.66
44.44
MCD
McDonald's
92.81
93.53
TSLA
Tesla Motors
259.28
AAPL
Apple Inc
100.80
102.30
Tesla Motors is missing one price line:
TSLA
Tesla Motors
259.28
AAPL
Therefore you try to convert AAPL to double.
If this is normal, you should use hasNextDouble() method before reading the price.
I want to read contents from a text file and then set it to some variables in car class. But it keeps showing me that "java.lang.NullPointerException". I don't know what's wrong with it. Could someone tell me what to do?
The error line is cars[0].setRegion(tokens[2]);
Here's the text file.
CarInLot KLM456 ND Meter4 120
CarInLot VMK123 ME Moving 0
CarInLotDKC003 WA Meter5 30
Meter1 None 10
CarInLot IML84U ND Meter6 800
Here's the test class.
import java.util.Scanner;
import java.io.*;
public class test
{
public static void main(String[] args) throws IOException
{
// Get the filename.
String filename = "input.txt";
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
if(filecotent.startsWith("Meter")){
cars[0].setPlate(tokens[1]);
}
}
System.out.println(cars[0].toString());
// Close the file.
inputFile.close();
}
}
Here's car class.
public class Car {
private String plate;
private String region;
private int minutes;
public Car(String carPlate, String carRegion,
int carMinutes) {
plate = carPlate;
region = carRegion;
minutes = carMinutes;
}
public Car(Car object2) {
plate = object2.plate;
region = object2.region;
minutes = object2.minutes;
}
public void setPlate(String pl) {
plate = pl;
}
public void setRegion(String re) {
region = re;
}
public void setMinutes(int mi) {
minutes = mi;
}
public String getPlate() {
return plate;
}
public String getRegion() {
return region;
}
public int getMinutes() {
return minutes;
}
public String toString() {
String string = "Car's information: "
+ "\n"
+ "\nLicense Plate: " + plate
+ "\nLicense Plate Resgistration Region: " + region
+ "\nParked time" + minutes
+ "\n";
return string;
}
}
So you've got this code
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
...
cars is initialized, but the elements inside it aren't. You need to initialize those first, otherwise they are null and you get NullPointerException.
cars[someIndex] = new Car(...);
Also, the way you have your code now, you'll always be overwriting the same Car reference in the array, ie. the one at index 0. You may want to use an incrementing index to initialize each element.