public class HashMapTest2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter total player");
Integer p = s.nextInt();
System.out.println("Enter total Team");
Integer t = s.nextInt();
List<String> listp = new ArrayList<>();
for (int i = 1; i<p; i++){
System.out.println("Enter Player name "+i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 1; i<t; i++){
System.out.println("Enter Team name "+i);
listt.add(s.nextLine());
}
}
}
我得到一些奇怪的输出,如下所示:
Enter total player
3
Enter total Team
2
Enter Player name 1
Enter Player name 2
pari
Enter Team name 1
为什么程序要求我两次输入播放器名称?第一次,它要求输入两次播放器名称,但我不知道为什么。有什么办法解决这个问题?
答案 0 :(得分:1)
在使用nextInt()
时,将读取整数值,但不读取行尾字符(返回/回车),将代码更改为使用nextLine()
进行如下正确处理。
public static void main(String... obj) {
Scanner s = new Scanner(System.in);
System.out.println("Enter number of Players");
Integer p = Integer.valueOf(s.nextLine());
System.out.println("Enter number of Teams");
Integer t = Integer.valueOf(s.nextLine());
List<String> listp = new ArrayList<>();
for (int i = 0; i < p; i++){
System.out.println("Enter Player name " + i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 1; i < t; i++){
System.out.println("Enter Team name " + i);
listt.add(s.nextLine());
}
}