0

why I cannot assign value on name[0] using for loop? Below is my code. And my code only accepts number of names 1 less the user input. for example the user wants to input 4 names my code only accepts 3 names and assigns them to name[1],name[2],name[3].

import java.util.Scanner;
public class Application {
    public static void main(String[] args) {

        Scanner input=new Scanner(System.in);
        System.out.println("How many Students?");
        int noOfStudents=input.nextInt();
        String[] name= new String[noOfStudents];
        System.out.println("Enter student names:");

        for(int x=0; x!=name.length;x++){
            name[x]=input.nextLine();
        }
        System.out.println("Names are:");
        for(String names: name){
            System.out.println(names);
        }
    }
}
Pramod Karandikar
  • 4,949
  • 6
  • 37
  • 60

1 Answers1

2

After getting the integer input, clear away the '\n' (new line) character using input.nextLine();

int noOfStudents=input.nextInt();
String[] name= new String[noOfStudents];
System.out.println("Enter student names:");
// Add this
input.nextLine() // Clear away the new line character following your integer input
almightyGOSU
  • 3,698
  • 6
  • 27
  • 39