Sunday, 15 September 2013

Java While-Loop issue

Java While-Loop issue

I am trying to read a .txt file which contains this
lollipops 10 0.50 5.00
dietsoda 3 1.25 3.75
chocolatebar 20 0.75 15.00
What it will do is make 4 columns one for name, quantity, price, total and
read them from the txt file. Then calculate subtotal, sales tax and then
total. I'm having a problem trying to use a while loop to read each line,
I keep getting an infinite loop.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CatalogTester
{
public static double SALESTAX = 0.0625;
public static void main(String[] args) throws FileNotFoundException
{
String name ="";
int quantity = 0;
double price =0;
double total = 0;
double subtotal = 0;
double tax = 0;
double total_all = 0;
File inFile = new File("Catalog.txt");
Scanner in = new Scanner(inFile);
String line = in.nextLine();
while(in.hasNextLine()){
int i = 0;
while(!Character.isDigit(line.charAt(i))) {i++;}
name = line.substring(0,i);
int j = line.length()-i;
while(Character.isDigit(line.charAt(j))) {j++;}
String quantityVal = line.substring(i, j);
quantity = Integer.parseInt(quantityVal);
int k = j;
while(Character.isDigit(line.charAt(k))) {k++;}
int x = k+4;
while(Character.isWhitespace(line.charAt(x))) {x++;}
String priceVal = line.substring(k,x);
price = Double.parseDouble(priceVal);
int z = x;
while(Character.isDigit(line.charAt(z))) {z++;}
String totalVal = line.substring(z,line.length());
total = Double.parseDouble(totalVal);
}
System.out.printf("%-30s %-10s %-10s %-10s\n", "Item",
"Quantity","Price", "Total");
System.out.println();
System.out.println("Expected:Item
Quantity Price Total");
System.out.printf("%-30s %-10d %-10.2f %-10.2f\n", name, quantity,
price, total);
System.out.println("Expected:lollipops 10
0.50 5.00");
System.out.printf("%-52s %-10.2f\n", "SubTotal", subtotal);
System.out.println("Expected:SubTotal
23.75");
System.out.printf("%-52s %-10.2f\n", SALESTAX * 100 + "% Sales
Tax",tax);
System.out.println("Expected:6.25% Sales Tax
1.48");
System.out.printf("%-52s %-10.2f\n", "Total", total_all);
System.out.println("Expected:Total
25.23");
}
}

No comments:

Post a Comment