0

我正在尝试读取包含此内容的 .txt 文件

lollipops 10 0.50 5.00 
dietsoda 3 1.25 3.75
chocolatebar 20 0.75 15.00

它会做的是为名称、数量、价格、总计创建 4 列,然后从 txt 文件中读取它们。然后计算小计,销售税,然后总计。我不确定如何计算小计,因为总和始终是最后一个值,在这种情况下是巧克力棒的总和。

    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);
        System.out.printf("%-30s %-10s %-10s %-10s\n", "Item", "Quantity","Price", "Total");
        System.out.println();
        System.out.println("Expected:Item                           Quantity   Price      Total");
        while(in.hasNext()){
            name = in.next();
            quantity = in.nextInt();
            price = in.nextDouble();
            total = in.nextDouble();
            System.out.printf("%-30s %-10d %-10.2f %-10.2f\n", name, quantity, price, total);
        }
        in.close();
        tax = subtotal * SALESTAX;
        total_all = subtotal+tax;


        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");    
    }
}
4

3 回答 3

0

你永远不会重新分配line. 因此,每次都会检查相同的第一行。

String line = in.nextLine();
while(in.hasNextLine()){
   int i = 0;
   while(!Character.isDigit(line.charAt(i))) {i++;} //<--- same line

要解决这个问题:

String line = in.nextLine();
    while(in.hasNextLine()){
       int i = 0;
       while(!Character.isDigit(line.charAt(i))) {i++;}
      //code
       line = in.nextLine(); //added
     }
于 2013-09-16T04:55:01.667 回答
0

您没有在while循环中读取任何行...

你可能错过了说:

line = in.nextLine();

接近循环的尽头。

于 2013-09-16T04:56:15.203 回答
0

在 while 条件下移动行分配。

      String line = in.nextLine();
         while(in.hasNextLine()){

改成

      while(in.hasNextLine()){
         String line = in.nextLine();
于 2013-09-16T05:11:28.817 回答