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());
}
}
}
I am getting some strange outputs, like the ones below:
Enter total player
3
Enter total Team
2
Enter Player name 1
Enter Player name 2
pari
Enter Team name 1
For the first time it is asking for player's name twice and I don't know why. Any way to solve this?
When you are using nextInt()
then the integer value is read but not the end-of-line character (Return/Enter) change your code to use nextLine()
as below for correct handling.
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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.