0

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.

3 Answers3

0

just replace sc.next() by sc.nextLine()

heyhooo
  • 82
  • 6
0

This is because nextLine() required. But be aware use it, documentation say that:

Advances this scanner past the current line and returns the input * that was skipped.

This method returns the rest of the current line, excluding any line * separator at the end. The position is set to the beginning of the next * line.

Known that you should use before loop and problem will be solved.

Scanner sc = new Scanner(System.in);
System.out.print("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
sc.nextLine();
for (int i = 0; i < size; i++) {
    System.out.println("Please write a name:");
    indoor_games[i] = new Indoor(sc.nextLine());
}
evigis
  • 3
  • 2
0

Hey thanks for the answers and help. It was actually a compilation problem, I was compiling the package in a wrong way. It's working now.