I am simply trying to access my array(items[j]) which I filled by doing this:
for(int j = 0;j<items.length;j++){
for(int i = 0;i<prices.length;i++){
items[j] = x.next();
System.out.print(items[j] + ", ");
prices[i] = c.nextDouble();
System.out.printf("$%.2f \n", prices[i]);
The Code above works as intended, however a 'null' problem occurs when I try access the array(items[j]) outside the for loop. Like this:
System.out.printf("%s, ", items[5]); //accessing 6th item on the menu(Coffee)
System.out.printf("$%.2f", prices[5]); //accessing 6th items price.(2.59)
My Output:
null, $2.59
It seems to work for the Prices array, just not for the Items array.
My Expected Output:
Coffee, $2.59
Here is my full code if there is any confusion:
int size = 1000;
String [] items = new String[10];
double [] prices = new double[size];
System.out.println(" ");
File fileText = new File("inventory.txt");
Scanner x = new Scanner(fileText);
x.useDelimiter("[^A-Za-z]+" + "[^A-Z a-z]+");
Scanner c = new Scanner(fileText);
c.useDelimiter("[^0-99.99]+");
try{
System.out.println("The items in inventory.txt are: ");
while(x.hasNext()&&c.hasNext()){
for(int j=0;j<items.length;j++){
for(int i = 0;i<prices.length;i++){
items[j] = x.next();
System.out.print(items[j] + ", ");
prices[i] = c.nextDouble();
System.out.printf("$%.2f \n", prices[i]);
}
}
}
x.close();
c.close();
}
catch(NoSuchElementException g){
System.out.println(" ");
}
System.out.printf("%s, ", items[5]); //accessing 6th item on the menu(Coffee)
System.out.printf("$%.2f", prices[5]); //accessing 6th items price.(2.59)
The text file my program is reading, (inventory.txt):
Espresso, 2.10
Mochaccino, 5.99
Irish Coffee, 7.99
Caffe Americano, 6.40
Latte, 1.99
Coffee, 2.59
Cappuccino, 3.50
blackCoffee, 8.90
whiteCoffee, 5.54
yellowCoffee, 4.80
greenCoffee, 6.12
purpleCoffee, 3.54