While循环与hasNext(); 不完全循环(While loop with hasNext

2019-10-28 08:58发布

我是在创造一个程序,从外部文件中读取数据,内部的文件,然后将结果打印到一个新的外部文件时,它与其他数据进行比较的过程。 我有我的代码while循环部分的问题。 我不确定它是否是while循环本身或for循环被嵌套。 下面是代码:

public class WageCalculator {

  public static void main(String[] args) throws FileNotFoundException {

    Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
    PrintWriter output = new PrintWriter("wagedaily.txt");

    float RecommendedMaximum;
    RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter the recommended maximum journey cost:"));

    String ShipID, JourneyID; //Variables
    int JourneyLength, Crew;
    double RateOfPay, CrewCost, TotalCost;

    while (input.hasNext()) { //EOF-Controlled While Loop
      ShipID = input.nextLine();
      JourneyID = input.nextLine();
      JourneyLength = input.nextInt();
      Crew = input.nextInt();

      CrewCost = 0; //Default Values Set
      TotalCost = 0;
      for (int x = Crew; x > 0; x--) { //For Loop updates the above values
        RateOfPay = input.nextDouble();
        CrewCost = RateOfPay * JourneyLength;
        TotalCost = TotalCost + CrewCost;
      }

      if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
        System.out.println("The total cost of...");
        output.println("The total cost of...");
      } else if (TotalCost == RecommendedMaximum) {
        System.out.println("The total cost of...");
        output.println("The total cost of...");
      } else {
        System.out.println("The total cost of...");
      }
    }

    output.close(); //Close both Scanner and Printwriter
    input.close();
  }

}

我得到的错误是这样的:

Exception in thread "main" java.util.InputMismatchException  
at java.util.Scanner.throwFor(Unknown Source)  
at java.util.Scanner.next(Unknown Source)  
at java.util.Scanner.nextInt(Unknown Source)  
at java.util.Scanner.nextInt(Unknown Source)  
at (package).WageCalculator.main(WageCalculator.java:30)

错误说这是行30在我的代码,这是问题,但我不那么肯定。

柜面任何人需要看到TestData.txt文件:

Monarch  //ShipID
M141     //JourneyID
16       //JourneyLength
6        //Crew
10.5     //RateOfPay -
10.5
20
20
20
30       //- RateOfPay
Princess //ShipID
P103     //JourneyID
18       //JourneyLength
5        //Crew
40       //RateOfPay -
45
45
60
80       //- RateOfPay

任何帮助,将不胜感激 :)

Answer 1:

你正在做一堆input.nextXXX()检查后,在循环中调用input.hasNext()只有一次在循环的顶部。 不这样做,因为这是非常不安全的,注定要失败,并且应该永远是一个检查和一个GET之间有一个一一对应。 举例来说,如果你想获得下一行,应该有一个input.HasNextLine()调用之前调用称为input.nextLine() 同为input.next()input.nextInt()

我自己,我会通过检查行读取线hasNextLine()然后一旦在读nextLine()然后操纵字符串接收。

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

   // now do not use input further within the loop
}

然后,您可以在循环中使用第二扫描仪使用所接收的线路,或通过分割线String#split(String regex)或做任何你需要做的事。

或者你可以用String replaceAll(...)和正则表达式来摆脱所有空格后面加上“//”后面的任何字符的。 例如,

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

     // get rid of white space followed by "//" followed by anything
     line = line.replaceAll("\\s+//.*", "");
     System.out.println(line);
  }

编辑
我已经看了多地进入你的问题,你的数据了一下,我要修改我的回答。 如果您是绝对确保您的数据文件的完整性 ,可以考虑每获得整船的数据一次检查nextline。 例如:

public static void main(String[] args) {
  InputStream inStream = GetData.class.getResourceAsStream(DATA_FILE);
  List<Cruise> cruiseList = new ArrayList<>();
  Scanner input = new Scanner(inStream);
  while (input.hasNext()) {
     String name = getLine(input);
     String id = getLine(input);
     int length = Integer.parseInt(getLine(input));
     int crew  = Integer.parseInt(getLine(input));

     // assuming a class called Cruise
     Cruise cruise = new Cruise(name, id, length, crew);

     for (int i = 0; i < crew; i++) {
        cruise.addPayRate(Double.parseDouble(getLine(input)));
     }

     cruiseList.add(cruise);
  }

  input.close();
}

private static String getLine(Scanner input) {
  String line = input.nextLine();

  // get rid of white space followed by "//" followed by anything
  line = line.replaceAll("\\s+//.*", "");
  return line;
}


Answer 2:

它给你带来麻烦的原因是因为当用户输入然后整数点击进入,两件事情刚刚进入 - 整数和“换行”,这为\ n。 您所呼叫的方法,“nextInt”,只读取的整数,这让输入流中的换行符。 但调用nextLine()不读入新行,这就是为什么你必须调用nextLine()之前,你的代码会工作。 你可能也被称为下一个(),这也已经在读换行符。

也读做进一步的了解扫描仪类的文档:

下面是更正后的代码:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class WageCalculator {

      public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
        PrintWriter output = new PrintWriter("wagedaily.txt");

        float RecommendedMaximum;
        RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null, 
                                                "Enter the recommended maximum journey cost:"));

        String ShipID, JourneyID; //Variables
        int JourneyLength, Crew;
        double RateOfPay, CrewCost, TotalCost;

        while (input.hasNext()) { //EOF-Controlled While Loop
            System.out.println("While Enter"); // For debugging purpose
            ShipID = input.nextLine();
            JourneyID = input.nextLine();
            JourneyLength = input.nextInt();
            input.nextLine();     // Enter this to read the data of skipped Line
            Crew = input.nextInt();
            input.nextLine();
            CrewCost = 0; //Default Values Set
            TotalCost = 0;
            for (int x = Crew; x > 0; x--) { //For Loop updates the above values
                System.out.println("While Under if Enter");// For debugging purpose
                RateOfPay = input.nextDouble();
                input.nextLine();
                CrewCost = RateOfPay * JourneyLength;
                TotalCost = TotalCost + CrewCost;
                System.out.println("While Under if Exit");// For debugging purpose
            }

            if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
                output.println("The total cost of...");
            } else if (TotalCost == RecommendedMaximum) {
                System.out.println("The total cost of...");
                output.println("The total cost of...");
            } else {
                System.out.println("The total cost of...");
            }
            System.out.println("While Exit"); // For debugging purpose
        }    
        output.close(); //Close both Scanner and Printwriter
        input.close();
    }

}


文章来源: While loop with hasNext(); not fully looping