5

Sir i am trying to print array's 0th element but i can't. Here is my code

import java.util.Scanner; public class prog3 { public static void main (String[] args){ Scanner input = new Scanner(System.in); int size = input.nextInt(); String arr[] = new String[size]; for (int i=0; i<size; i++){ arr[i]= input.nextLine(); } System.out.print(arr[0]); } } 

when i am trying to print arr[0] its return blank but when i print arr[1] it returns the 0th element value. would you please help me to find my error.

2
  • Sir i am new in java.Would you please explain the reason ? Commented Dec 11, 2013 at 13:19
  • see my edited answer for more information. Commented Dec 11, 2013 at 13:23

3 Answers 3

5

Change

arr[i]= input.nextLine(); 

to

arr[i]= input.next(); 

and it works. this is because nextLine() reads a whitespace and then it looks like arr[0] is empty. You can see this, because if the size is 3 you can input only two times. See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html for more information about scanner :)

Sign up to request clarification or add additional context in comments.

3 Comments

Why does that work. Please explain your answer :)
Yes its working . Thank you so much .. would you please explain why nextLine() is not working
Are you sure he doesn't want to read lines containing ws? Since this would tokenize input with spaces, for example.
2

Try this mate:

 input.nextLine(); // gobble the newline for (int i = 0; i < size; i++) { arr[i] = input.nextLine(); } 

1 Comment

the nextLine() method is a bit quirky, since there was a newline "hanging" after nextInt(). If you gobble it up, things should then work as you expect.
2

Corrected code: Include input.nextLine(); after input.nextInt()

import java.util.Scanner; public class prog3{ public static void main (String[] args){ Scanner input = new Scanner(System.in); int size = input.nextInt(); input.nextLine(); String arr[] = new String[size]; for (int i=0; i<size; i++){ arr[i]= input.nextLine(); } System.out.print(arr[0]); } } 

Input :

2 45 95 

Output

45 

Explanation:

The problem is with the input.nextInt() command it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Scanner issue when using nextLine after nextXXX

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.