First element of string array printing null. Please explain why it is not printing the first element of string array.
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
String[] array = new String[aa];
System.out.println("Please enter 20 names to sort");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
}
System.out.println(array[0]);
}
The problem is that you are not giving a valid integer when constructing the String array. Instead of aa
, you should have a number. Since you ask for 20 names, then you should declare an array of size 20.
Edit: Assuming aa
is user input, you just need to consume the next line after reading. Note that this also happens when using nextDouble with the scanner.
public static void main(String[] args) throws Exception
{
Scanner s = new Scanner(System.in);
System.out.println("How many names would you like to enter?");
int aa = s.nextInt();
//must include since nextInt leaves the new line
s.nextLine();
String[] array = new String[aa];
System.out.println("Please enter " + aa + " names to sort");
for (int i = 0; i < array.length; i++)
{
array[i] = s.nextLine();
}
System.out.println(array[0]);
}
Also, please note that the array will not sort itself! You'll have to implement that later.
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.