2017-05-27 47 views
-1

當我有這個節目扭轉字的順序,但輸入被弄亂了。這是我的輸出日誌。異常在線程「主」 java.util.InputMismatchException使用掃描儀

1 
this is a trial 
Exception in thread "main" java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:864) 
    at java.util.Scanner.next(Scanner.java:1485) 
    at java.util.Scanner.nextInt(Scanner.java:2117) 
    at java.util.Scanner.nextInt(Scanner.java:2076) 
    at Store_Credit.main(Store_Credit.java:13) 

Process finished with exit code 1 

而且,這裏是我的代碼:

import java.util.Scanner; 

public class Reverse_Words { 

    public static void main(String[] args) { 
     Scanner scanner = new Scanner(System.in); 
     int N; 
     N = scanner.nextInt(); 
     for(int i = 0; i < N; i++) { 
      int h = i+1; 
      String[] s = scanner.nextLine().split(" "); 
      System.out.print("Case #"+h+": "); 
      for(int j = s.length-1; j >=0; j++) { 
       System.out.print(s[j]+" "); 
      } 
      System.out.println(); 
     } 
    } 
} 
+0

您堆棧跟蹤不匹配你的代碼 –

+2

'Scanner.nextInt()'消耗您鍵入的數目,但_不是回車。您通過調用'Scanner#nextLine()'來獲取回報。 –

+0

這個異常不會引發您輸入的內容。不過,另一個是拋出。你是否真的輸入1並在執行時按下Enter鍵? –

回答

-1

嘗試執行此檢查,如果你仍然可以在最後的錯誤

public static void main(String[] args) { 
     @SuppressWarnings("resource") 
     Scanner scanner = new Scanner(System.in); 
     int n; 
     System.out.println("enter number"); 
     n = scanner.nextInt(); 
     for(int i = 0; i < n; i++) { 
      int h = i+1; 

      System.out.println("enter string"); 

      String[] s = scanner1.nextLine().split(" "); 
      System.out.print(s.length); 
      System.out.print("Case #"+h+": "); 
      for(int j = s.length-1; j >=0; j--) { 
       System.out.print(s[j]+" "); 
      } 
      System.out.println(); 
     } 
    } 

遞減Ĵ值循環,即,J - (不是J ++)

+1

在問題的代碼不扔提到的錯誤。有兩臺掃描儀是不必要的 –

+0

是的,你是對的。我意識到這一點。由於我沒有得到上述錯誤,我不完全確定代碼出了什麼問題。所以我給了一個正確運行的代碼。 –

+1

你的代碼沒有工作:)謝謝你的嘗試。 –

相關問題