I'm trying to store input in the array indoor_games and output it to the screen, but when I'm executing the code, it abruptly ends the execution after accepting 1 value.
package games;
import java.util.*;
import java.lang.*;
class Indoor{
String name;
Indoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Outdoor{
String name;
Outdoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
for(int i=0;i<size;i++){
name = sc.next();
indoor_games[i] = new Indoor(name);
}
for(int i=0;i<size;i++)
indoor_games[i].display();
}
}
Updated code with nextLine added but still the same problem:
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
sc.nextLine(); //To consume the newline character
Indoor[] indoor_games = new Indoor[size];
for(int i = 0 ; i < size ; i++){
name = sc.nextLine();
indoor_games[i] = new Indoor(name);
}
for(int i = 0 ; i < size; i++)
indoor_games[i].display();
}
}
Output(Command Line)
D:\Docs Dump\School stuff\JAVA\Java slips>java games.Slip20
Enter number of Players in Indoor Games:
3
Neeraj
D:\Docs Dump\School stuff\JAVA\Java slips>
As you can see, the scanner only accepts "Neeraj" and the program ends
execution.