2013-07-29 31 views
1

我在一起簡單的Java程序來解釋循環。我希望每個演示都在一個單獨的功能中。現在,每個函數都可以正常工作,但只有當另一個函數沒有被調用時。如果我打電話我都得到了以下錯誤在運行時:調用函數給出「NoSuchElementException」

Please input a positive integer as the end value: 5 
The summation is: 9 
How many rows do you want your triangle to be?: Exception in thread "main" java.util.NoSuchElementException 
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 loops.exercise2(loops.java:48) 
at loops.main(loops.java:11) 

代碼:

import java.util.Scanner; 

public class loops 
{ 

public static void main(String args[]) 
{ 
    exercise1(); 
    System.out.println(); 
    exercise2(); 
} 

public static void exercise1() 
{ 

    int limit; 
    int i; 
    int sum; 

    Scanner keyboard = new Scanner(System.in); 


    System.out.print ("Please input a positive integer as the end value: "); 

    limit = keyboard.nextInt(); 

    i=1; 
    sum = 0; 

    while (i <= limit) 
    { 
     sum = sum + i; 
     i = i + 2;   
    } 

    System.out.print("The summation is: " + sum); 

    keyboard.close(); 
} 

public static void exercise2() 
{ 
    int numRows, i, j; 
    Scanner keyboard = new Scanner(System.in); 

    System.out.print("How many rows do you want your triangle to be?: "); 
    numRows = keyboard.nextInt(); 

    for(i=0; i<numRows; i++) 
    { 
     for(j=0; j<=i; j++) 
     { 
      System.out.print("*");    
     } 
     System.out.println(); 
    } 

    keyboard.close(); 
} 

}

+0

提示:下一次,使用更短的標題! =) –

+1

這是因爲兩種方法都在等待掃描器輸入(這是您的控制檯輸入),並且出現了干涉對方 – bas

回答

3

這是發生,因爲當你關閉你的掃描儀,它也關閉輸入流,在這種情況下是System.in。當你嘗試在你的execise2方法中實例化掃描器時,輸入流被關閉。

看到這個SO發佈...

https://stackoverflow.com/a/13042296/1246574

+0

謝謝。這解決了這個問題,但它並沒有產生新的問題:什麼時候有人想關閉掃描儀?如果垃圾回收器確保沒有內存泄漏,關閉掃描器意味着您不能再使用System.in,何時關閉它是個好主意? – user2112156

+0

除SystemIn外,您還可以將掃描儀與其他類型的輸入流一起使用,並且在許多情況下,當您完成掃描儀時,最好關閉底層輸入流。這個鏈接中有一些例子... http://docs.oracle.com/javase/tutorial/essential/io/scanning.html – Jim

1

我的猜測是你的掃描儀類相互干擾。 exercise1從標準輸入中輸入,然後關閉。然後exercise2也嘗試從已關閉的標準中獲取輸入。

我建議你只製作1個掃描儀,並將它作爲參數傳遞給exercise1和exercise2,然後在兩次調用後關閉它。

1

製作全局掃描程序,並只啓動一次,然後調用其方法。

1

儘量不要打電話keyboard.close();

相關問題