2016-07-13 33 views
1

我已經得到了避免環路從輸入最後一行的問題。最後輸入的行不包括在環路

例輸入:

+ 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); 
     } 
} 

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

+1

因爲沒有下一行後最後一個!嘗試在上次輸入後輸入一個空行;) –

+0

這是在我的月食沒有任何更正。請再運行一次。 –

回答

0

我有同樣的問題與掃描儀。 nextInt()命令不會讀取回車,因此它將輸入命中作爲下一個掃描器的輸入。 嘗試添加「String trash = reader.nextLine();」每隔一次之後。 至少,這幫助我與我的掃描儀問題:)

0
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])); 
    ... 
}