[英]Java Scanner not accepting input after the For loop
我目前正在開發一個程序,要求輸入兩個團隊的名稱和分數。 當我要求輸入一隊的名稱和9分時,掃描程序會接受輸入。 但是,在for循環之后,掃描程序將不接受第二組名稱的輸入。 這不是整個程序,但是我已經包括了所有代碼,直到給我造成麻煩為止。 我懷疑它可能與for循環有關,因為當我將其放置在for循環之前時,team2可以接受用戶輸入。
import java.util.Scanner;
public class sportsGame{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String team1;
String team2;
int team1Scores[] = new int[9]
int team1Total = 0;
int team2Scores[] = new int[9];
int team2Total = 0;
System.out.print("Pick a name for the first team: ");
team1 = input.nextLine();
System.out.print("Enter a score for each of the 9 innings for the "
+ team1 + " separated by spaces: ");
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
System.out.print("Pick a name for the second team: ");
team2 = input.nextLine();
}
}
掃描儀的nextInt方法不跳過一行,僅獲取int。 因此,當第一個循環結束時,仍然剩下一個換行符,而您的input.nextLine()返回一個空字符串。 在循環后添加一個input.nextLine(),以跳過此空行並解決如下問題:
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
input.nextLine();
//rest of your code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.