簡體   English   中英

最后一行輸入未包含在循環中

[英]Last line of input not included in the loop

我遇到的問題是循環中避免了輸入的最后一行。

輸入示例:

+ 2 3
* 23 23 
/ 65 54
+ 23 23

計划給了我:

5
529
1

為什么不計算最后一行?

Scanner input = new Scanner(System.in);
for(int i = 0; input.hasNextLine(); i++){
        char c = input.next().charAt(0);
        int x = input.nextInt();
        int y = input.nextInt();

        if( c == '*'){
            System.out.println(x*y);
        }
        else if(c == '/'){
            System.out.println(x/y);
        }
        else if(c == '-'){
            System.out.println(x-y);
        }
        else if(c == '+'){
            System.out.println(x+y);
    }
        else if(c == '%'){
            System.out.println(x%y);
        }   
}

我也測試了循環,它完全一樣。 能否請你幫忙?

我和Scanner有同樣的問題。 命令nextInt()不讀取輸入,因此它將輸入命中作為下一個掃描程序的輸入。 嘗試添加“String trash = reader.nextLine();” 在每個nextInt之后。 至少這對我的掃描儀問題有幫助:)

BufferedReader br = new BufferedReader(new FileReader(new File("data")));
String line = "";
while((line=br.readLine())!=-1){
   String[] data = line.split(" ");
   if(data[0].compareTo("+")==0)
     System.out.println(Integer.parseInt(data[1])+Integer.parseInt(data[2]));
   if(data[0].compareTo("*")==0)
     System.out.println(Integer.parseInt(data[1])*Integer.parseInt(data[2]));
   ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM