2015-02-10 100 views
0

我無法弄清楚如何允許輸入包含用戶想要的行數。輸入將由至少1行組成。在第一行將是一個整數,這個整數是假設告訴程序後面會有多少行,例如。我如何使用多個掃描儀

5 
    line1 
    line2 
    line3 
    line4 
    line5 

我該怎麼辦?有沒有一種掃描儀可以讓我使用循環或者應該使用循環?

回答

1

您不需要多個Scanner實例來處理這個問題。只需使用一個循環就足夠了。

Scanner sc = new Scanner(System.in); 
int nbLines = sc.nextInt(); 
sc.nextLine(); //consume the line separator token 
for(int i = 0; i < nbLines; i++) { 
    String line = sc.nextLine(); 
    //do something with the line 
} 
+0

謝謝!它幫助了我,現在我終於可以完成該計劃。 – 2015-02-10 01:45:42