2015-09-28 168 views
0

我的應用程序在main中遇到scan.getLine()時總是崩潰。 我得到的錯誤是「java.util.NoSuchElementException:No line found」。Java應用程序在nextLine上崩潰()

下面是代碼:

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    String s = new String(); 
    int operation=0; 
    operation = getOperation(); 
    System.out.print("Enter string:"); 
    s = scan.nextLine(); // program crashes before I have the chance to input anything 
    System.out.println(s); 
    scan.close(); 

} 
public static int getOperation(){ //get operation between 1-10 
    Scanner scan= new Scanner(System.in); 
    boolean input=true; 
    int op=0; 
    while (input){ // get correct input from the user 
     if (scan.hasNextInt()) 
     { 
      op=scan.nextInt(); 
      if (op < 1 || op > 10) 
       System.out.print("Please enter valid operation 1-10:"); 
      else 
       input=false; 
     } 
     else 
      System.out.print("Please enter valid operation 1-10:"); 
     scan.nextLine(); // to clear the buffer 
    } 
    scan.close(); 
    return op; 
} 

奇怪的是,當我插入之前,我寫getOperation功能,整個getOperation在裏面main,應用程序正常工作。只有當我將代碼移動到getOperation方法後,然後scan.nextLine()崩潰,甚至沒有改變以在控制檯中輸入任何東西。

+0

嘗試宣告1'Scanner'對象(一個主用),並把它傳遞給'getOperation '方法。 – npinti

回答

0

嘗試使用這個小小的代碼段

public static void main(String[] args) { 
    Scanner s1 = new Scanner(System.in); 
    Scanner s2 = new Scanner(System.in); 
    s2.close(); 
    s1.nextLine(); 
} 

的關閉功能關閉的InputStream System.in

因爲你是在getOperation()另一掃描儀關閉掃描儀scan.close();一個以下調用具有相同的InputStream會導致你遇到的異常。

0

你不需要在主要的Scanner

public static void main(String[] args) { 
    String s = new String(); 
    System.out.print("Enter string:"); 
    int operation = 0; 
    operation = getOperation(); 
    s = "" + operation; // program crashes before I have the chance to input anything 
    System.out.println(s); 
} 

輸出:

Enter string:11 
Please enter valid operation 1-10:1 
1