Reading Multiple Values Into Array Error - java

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.

Related

How to insert value from user defined datatypes to object in java?

I'm creating an object of type Lightmode, which is a class.
There's also a Smartlamp class which is having a variable of custom data of type Lighmodes and I want to show my defined data type value over there.
I'm trying to create an object and then insert a string against my Lightmode data type which is showing error. I want to print like this:
Name:  lamp1 
Location: 3.1 
Switched On:  false 
Mode:  STANDARD 
Here mode is lightmode datatype and I'm getting a problem over it.
...
public class LightModes
{
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}...
...package smart.home.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size,mode;
int displayindex=1;
String name;
double location,temperature;
boolean status=false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size=in.nextInt();
// TODO code application logic here
SmartLamp[] smartLamp=new SmartLamp[size];// creating an array object of smartdevice class
//
for(int j=0;j<size;j++)
{
System.out.println("Enter Lamp name.");
name=input.readLine();
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation=new Scanner(System.in);
location=devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode=new Scanner(System.in);
mode=lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus=new Scanner(System.in);
int currentstatus=devicestatus.nextInt();
if(currentstatus==1)
{
status=true;
}
else if(currentstatus==0)
{
status=false;
}
LightModes light = null;
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}...
...public class SmartLamp extends SmartDevice{
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{"+"\nName."+getName()+"\nLocation."
+getLocation() + "\nSwitchedOn."+isSwitchedOn()+
"\nMode=" + getLightModes() + '}';
}
}...
I downloaded your code and added the missing class SmartDevice. Your code contains two compiler errors.
name = input.readLine();
This line throws java.io.IOException which is an unchecked exception and hence must be handled by your code. There are several ways to do this, one of which is to add throws IOException to method main() in class Step5.
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
The first argument to SmartLamp constructor is an instance of class LightModes but you are passing a String. You need to create an instance of LightModes.
Here is your code with my modifications that get rid of the two compiler errors.
(Note: The below code includes my guessed implementation of class SmartDevice.)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException { // Change here.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size, mode;
int displayindex = 1;
String name;
double location, temperature;
boolean status = false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size = in.nextInt();
SmartLamp[] smartLamp = new SmartLamp[size];// creating an array object of smartdevice class
for (int j = 0; j < size; j++) {
System.out.println("Enter Lamp name.");
name = input.readLine(); // throws java.io.IOException
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation = new Scanner(System.in);
location = devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode = new Scanner(System.in);
mode = lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus = new Scanner(System.in);
int currentstatus = devicestatus.nextInt();
if (currentstatus == 1) {
status = true;
}
else if (currentstatus == 0) {
status = false;
}
LightModes light = new LightModes(); // Change here.
light.setNIGHT_MODE(light.getNIGHT_MODE()); // Change here.
smartLamp[j] = new SmartLamp(light, name, location, status); // Change here.
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}
class LightModes {
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String name, double location, boolean switchedOn) {
this.name = name;
this.location = location;
this.switchedOn = switchedOn;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean isSwitchedOn() {
return switchedOn;
}
}
class SmartLamp extends SmartDevice {
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{" + "\nName." + getName() + "\nLocation." + getLocation()
+ "\nSwitchedOn." + isSwitchedOn() + "\nMode=" + getLightModes() + '}';
}
}

How to get user input and store in custom object? JAVA

Henlo,
Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());.
But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.
All the code that is meant to run should be inside the main method in Step1.java
Here are the 3 classes used for the code (ignore comments they are just notes for me):
package SmartHomeApp;
public class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
//YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {name = value;}
public void setLocation(double value) {location = value;}
public void setSwitchedOn(boolean value) {switchedOn = value;}
public String getName() {return name;}
public double getLocation() {return location;}
public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;
public class SmartHome
{
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {return smrtDev.length;}
// can't do toString() for some reason??
public void ToString() {
for(int i=0; i<size();i++)
{
if(smrtDev[i] != null ){
System.out.println("----------");
System.out.println("-DEVICE "+(i+1)+"-");
System.out.println("----------");
System.out.println("Name: "+smrtDev[i].getName());
System.out.println("Location: "+smrtDev[i].getLocation());
System.out.println("Switched On: "+smrtDev[i].getSwitchedOn());
}
}
}
}
package SmartHomeApp;
import java.util.*;
public class Step1 {
public static void main(String args[]) {
SmartHome app = new SmartHome(loadDataFromConfig());
app.ToString();
}
public static SmartDevice[] loadDataFromConfig()
{
SmartDevice[] dev = new SmartDevice[20];
dev[0] = new SmartDevice("device 1",1.3,true);
dev[1] = new SmartDevice("device 2",2.3,false);
dev[2] = new SmartDevice("device 3",3.3,true);
dev[4] = new SmartDevice("device 5",4.3,false);
dev[19] = new SmartDevice("device 20",5.3,false);
return dev;
}
}
Some of the improvements required in your code are as follows:
Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
Enter size:
2
Name:
Light Amplification by Stimulated Emission of Radiation
Location:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:83)
Given below is a sample code incorporating the improvements mentioned above:
import java.util.Scanner;
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
// YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {
name = value;
}
public void setLocation(double value) {
location = value;
}
public void setSwitchedOn(boolean value) {
switchedOn = value;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean getSwitchedOn() {
return switchedOn;
}
#Override
public String toString() {
return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
}
}
class SmartHome {
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {
return smrtDev.length;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (SmartDevice smartDevice : smrtDev) {
sb.append(smartDevice.toString()).append("\n");
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int size = getPositiveInt(myObj, "Enter size: ");
SmartDevice[] newList = new SmartDevice[size];
for (int i = 0; i < newList.length; i++) {
System.out.print("Name: ");
String x = myObj.nextLine();
double y = getFloatingPointNumber(myObj, "Location: ");
boolean z = getBoolean(myObj, "Is on?: ");
newList[i] = new SmartDevice(x, y, z);
}
SmartHome newDevice = new SmartHome(newList);
System.out.println(newDevice);
}
static int getPositiveInt(Scanner in, String message) {
boolean valid;
int n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Integer.parseInt(in.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("This in not a positive integer. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static double getFloatingPointNumber(Scanner in, String message) {
boolean valid;
double n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Double.parseDouble(in.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("This in not a number. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static boolean getBoolean(Scanner in, String message) {
System.out.print(message);
return Boolean.parseBoolean(in.nextLine());
}
}
A sample run:
Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]
So as suggested I tried to do the following:
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size: ");
int size = myObj.nextInt();
SmartDevice[] newList = new SmartDevice[size];
for(int i =0; i<newList.length;i++) {
System.out.println("Name: ");
String x = myObj.next();
System.out.println("Location: ");
double y = myObj.nextDouble();
System.out.println("Is on?: ");
boolean z = myObj.nextBoolean();
newList[i] = new SmartDevice(x,y,z);
}
SmartHome newDevice = new SmartHome(newList);
newDevice.ToString();
}
Got it working but not sure if this is the most efficient way to do so??

Why wont Eclipse #Override?

I am following along with the Java for Dummies book and I ran into a problem. I can't figure out why #Override isn't working. I'm sure it has to do with my code because I have gotten a polymorphic array to work with override before, but it was too simple for me to mimic.
import static java.lang.System.out;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class DoPayrollTypeP {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner diskScanner = new Scanner(new File("EmpInfoNew.txt"));
Scanner kbdScanner = new Scanner (System.in);
for(int empNum = 1; empNum<=3; empNum++){
payOneFTEmployee (diskScanner);
}
for(int empNum = 4; empNum<=6; empNum++){
payOnePTEmployee(diskScanner, kbdScanner);
}
}
public static void payOneFTEmployee(Scanner diskScanner){
FullTimeEmployee ftemployee = new FullTimeEmployee();
ftemployee.setName(diskScanner.nextLine());
ftemployee.setJobTitle(diskScanner.nextLine());
ftemployee.setWeeklySalary(diskScanner.nextDouble());
ftemployee.setBenefitDeduction(diskScanner.nextDouble());
diskScanner.nextLine();
diskScanner.nextLine();
ftemployee.cutCheck(ftemployee.findPaymentAmount());
out.println();
}
public static void payOnePTEmployee(Scanner diskScanner, Scanner kbdScanner) {
PartTimeEmployee ptemployee = new PartTimeEmployee();
ptemployee.setName(diskScanner.nextLine());
ptemployee.setJobTitle(diskScanner.nextLine());
ptemployee.setHourlyRate(diskScanner.nextDouble());
diskScanner.nextLine();
diskScanner.nextLine(); //Reads the dashed line that
// separates two employees
out.print("Enter ");
out.print(ptemployee.getName());
out.print("'s hours worked this week: ");
int hours = kbdScanner.nextInt();
ptemployee.cutCheck(ptemployee.findPaymentAmount(hours));
out.println();
}
}
Next class:
import static java.lang.System.out;
public class Employee {
private String name;
private String jobTitle;
public void setName(String nameIn) {
name = nameIn;
}
public String getName() {
return name;
}
public void setJobTitle(String jobTitleIn) {
jobTitle = jobTitleIn;
}
public String getJobTitle() {
return jobTitle;
}
public void cutCheck(double amountPaid){
out.printf("Pay to the order of %s", name);
out.printf("(%s) ***$", jobTitle);
out.printf("%,.2f\n", amountPaid);
}
}
Next Class:
public class PartTimeEmployee extends Employee{
private double hourlyRate;
public void setHourlyRate(double hourlyRateIn) {
hourlyRate = hourlyRateIn;
}
public double getHourlyRate() {
return hourlyRate;
}
public double findPaymentAmount(int hours){
return hourlyRate * hours;
} //method that should be overriden
}
Class That should override:
public class PartTimeWithOver extends PartTimeEmployee{
#Override
public double findPaymentAmount(int hours) {
if(hours <= 40) {
return getHourlyRate() * hours;
} else {
return getHourlyRate() * 40 +
getHourlyRate() * 2 * (hours - 40);
}
}
}
EmpInfoNew.(txt) file
jo shmo
Ceo
5000.00
500.00
edd shmoe
Captain
5000.00
500.00
bob shmo
Honorary Exec
1000.00
200.00
Dave shmo
driver
7.25
edd blah
Cook
8.50
len shmo
Head of Kitchen
12.50
You have instantiated object as
PartTimeEmployee ptemployee = new PartTimeEmployee();
It is a base class of PartTimeWithOther so it cannot call overridden method in derived class.
Change to
PartTimeEmployee ptemployee = new PartTimeWithOver();
Here is an nice tutorial with diagrams that explains Polymorphism
You never use PartTimeWithOver, you only work with PartTimeEmployee.
So your overriden method is never called.

My Tester Class in Incomplete and I'm trying to decide if I need to pull methods from my other classes

I am having problems deciding which methods I should pull out of my VendingMachine Class and placed in my TesterClass to test my program. I am attempting to test the VendingMachine and the Candy Classes by constructing Candy objects in my ArrayList but I'm not sure how to best accomplish this. The ArrayList of Candy objects contain the candy bar string and a double price. I want my tester to run the vending machine methods that prompt the user for the questions that are listed in the println methods.
Tester Class
public class Tester {
private static Object candyBarList;
public static void main(String args[])
{
WHAT METHODS SHOULD I PLACE HERE
}
Candy Class
public class Candy{
private double price;
private String candyBarName;
Candy()
{
price = 1.50;
candyBarName = "Pluto Bar";
//default constructor
}
Candy(double price1, String str){
price = price1;
candyBarName = str;
//constructor with parameters
}
public double getPrice(){
return price;
}
public void setPrice(double price){
this.price = price;
}
public String getCandyBarName(){
return candyBarName;
}
public void setCandyBarName(String candyBarName){
this.candyBarName = candyBarName;
}
Vending Machine Class
}
import java.util.ArrayList;
import java.util.Scanner;
import vendingmachine.Candy;
package vendingmachine;
/**
*
* #author admin
*/
public class VendingMachine {
double money = 0.0;
Candy candyBar = new Candy();
ArrayList<Candy> candyBarList = new ArrayList<>();
double cashBox = 0.0;
public VendingMachine(){
candyBarList.add(candyBar);
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
}
/**
* #return
*/
public double paymentIn(){
Scanner input = new Scanner(System.in);
//double payAmount=0.0;
System.out.println("Insert Money: ");
double payAmount = input.nextDouble();
return payAmount;
}
public static boolean isPaymentEnough(double depositMoney, double price){
if (depositMoney >= price)
{
return true;
}
else{
return false;
}
}
public void dispenseCandy (double depositMoney, Candy selectedCandy){
cashBox+= depositMoney - selectedCandy.getPrice();
candyBarList.remove(selectedCandy);
}
public String candySelector(){
for (int i=0; candyBarList.size() >= i; i++){
System.out.println(candyBarList.get(i));
}
Scanner input = new Scanner(System.in);
String candyBarSelected = input.next();
System.out.println("Please type in the Candy Bar you would like");
candyBarSelected = input.next();
return candyBarSelected;
}
public Candy findCandy(){
String candyName = candySelector();
for (int i=0; candyBarList.size() >= i; i++){
if (candyBarList.get(i).getCandyBarName().equals(candyName)){
return candyBarList.get(i);
}
}
System.out.println("Your selection is invalid");
return null;
}

make a global object in java

I want to make an array of objects and use it in different functions. I wrote this pseudocode
privat stock[] d;
privat stock example;
public void StockCheck(){
d =new stock[2];
d[0]= new stock("a","test1", 22);
d[1]= new stock("b","test2", 34);
}
#Override
public stock getStock(String name) throws StockCheckNotFoundException{
int i;
System.out.println("ok" + name + d.legth); // error
example = new stock("example","example",2);
return example;
}
In class test I make an instance of getStock and I call the function getStock stock.getStock();
I get a NullPointerExeption when I do d.length. d is null but I don't understand why.
Hmmmm. If that is in any way like your real code, then the problem is that your "constructor" isn't really a constructor, as you've declared it to return void, making it an ordinary method instead. Remove tbat "void" and it may fix the problem!
Perhaps this example of code will do what you need, using three classes
Test - the main test code
Stock - the implied code for Stock from your question
StockCheck - the corrected code from your question.
(Note: you may really want to use an ArrayList inside StockQuote so you can add and delete Stocks.)
Test class
package stackJavaExample;
public class Test {
public static void main(String[] args) {
String[] testNames = {"test1","test2","notThere"};
StockCheck mStockCheck = new StockCheck();
for (int i=0; i<testNames.length; i++) {
Stock result = mStockCheck.getStock(testNames[i]);
if (result == null) {
System.out.println("No stock for name: " + testNames[i]);
} else {
System.out.println("Found stock: " + result.getName() + ", " + result.getSymbol() + ", " + result.getValue());
}
}
}
}
Stock class
package stackJavaExample;
public class Stock {
private String symbol;
private String name;
private double value;
public Stock(String symbol, String name, double value) {
this.symbol = symbol;
this.name = name;
this.value = value;
}
public String getSymbol() { return symbol;}
public String getName() { return name;}
public double getValue() {return value;}
}
StockCheck class
package stackJavaExample;
public class StockCheck {
private Stock[] d;
public StockCheck() {
d = new Stock[2];
d[0] = new Stock("a","test1", 22);
d[1] = new Stock("b","test2", 34);
}
public Stock getStock(String name) {
for (int i=0; i < d.length; i++) {
if (d[i].getName().equalsIgnoreCase(name)) {
return d[i];
}
}
return null;
}
}

Categories

Resources