import java.util.*;
import java.util.Scanner;

public class InputconsoleArray2
    {
        public static void main(String args[]) throws java.io.IOException
        {
            int[] a=new int[100];								// create an array of type interger size
			// Objects of type Scanner are useful for breaking down formatted input into tokens and 
			// translating individual tokens according to their data type
			// By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, 
			// and line terminators. 
            Scanner sc=new Scanner(System.in);
            System.out.println("Please enter elements...");
			int j=0;
			//int next= sc.nextInt();
			//System.out.println("Next = " + next);
			while (  sc.hasNextInt())
			{
				a[j]=sc.nextInt();
				System.out.println(" a[j]  " + j +"  " + a[j]);	
				j++;
			}
			sc.close();
			int arrayCurrentSize = j--;
         	System.out.println("Array elements are : ");
            for (int i=0; i< arrayCurrentSize; i++)
			  System.out.println(a[i]);
       }
   }

Recommended Answers

All 10 Replies

Sorry for posting it so fast.
I am trying to read a user input from the console as integer numbers and store them into an array. I used the scanner method hasNextInt() to check when no more integer there, and stop the while loop then print the array.
I am getting Exception in thread "main" java.lang.array

Ah, I just ran your program an it worked fine for me. The only thing I see as weird is

int arrayCurrentSize = j--;

I believe this actually assigns arrayCurrentSize = j before j decrements (this is actually fine, there's no reason to reduce arrayCurrentSize since you correctly start at zero).

What did you use for your inputs, I used:
1 2 3
stop

My input is 10 20 30 40 50 60
but when I entered it from the command prompt it does not print the content of the array , it seem that the while loop does not terminate and it is waiting for more input. the only way to kill it is to inter a character and not an integer. sc.hasNextInt() suppose to return a boolean true if the next token is an integer and false if anything else including eol. I have been working on this problem for three hours with no luck.

the only way to kill it is to inter a character and not an integer. sc.hasNextInt() suppose to return a boolean true if the next token is an integer and false if anything else including eol.

Well apparently the last part is not correct. I just checked the API and it doesn't say such thing. It simply returns true or false if the next token is int BUT the the next token is not a new line. It is when you enter value. The new line, or many empty spaces followed by <ENTER> at the keyboard doesn't constitute as next token. Look at the description of the method:

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.

I understand that you want the user to enter this and stop at the New Line:

10 20 30

Instead of this:

10 20 30 a

Then perhaps you can try this:

Scanner KEY_BRD=new Scanner(System.in);
System.out.println("Please enter elements...");
String input = KEY_BRD.nextLine(); // enter 10 20 30 40
System.out.println("input: "+input );


Scanner sc = new Scanner([B]input[/B]);
int j=0;
			while (  sc.hasNextInt())
			{
				a[j]=sc.nextInt();
				System.out.println(" a[j]  " + j +"  " + a[j]);	
				j++;
			}

And Diomedes is right. You don't need to decrease the value of j. Whenever you add a number, you increase j. So at the end, the value of j gives you what you want

Well apparently the last part is not correct. I just checked the API and it doesn't say such thing. It simply returns true or false if the next token is int BUT the the next token is not a new line. It is when you enter value. The new line, or many empty spaces followed by <ENTER> at the keyboard doesn't constitute as next token. Look at the description of the method:

You might be saying the same thing, but just to clarify, the nextInt() method reads in the next token that is preceded and followed by the delimiter pattern. By default this pattern matches whitespace, so what this means is that as long as any amount and any kind of whitespace precedes and follows an integer, the nextInt() method will successfully read in that integer. This includes spaces, tabs, and newlines...

thanks, javaAddict
Sorry for not replying fast enough because of time difference. I modified my program as you suggested, but the compiler did not except it, problem at line Scanner sc = new Scanner([B] Illegal start of expression, and other errors relating to the same line.
Can you please explain what does this line do

You need a closing ). And why would you make a new Scanner that scans the string [COLOR="Green" anyway? That doesn't make any sense. Is that what you meant to put there?

It's a copy of a broken color tag from javaAddict's code above. The bold and color tags don't work right with the java syntax highlighting in code tags. That line should just read

Scanner sc = new Scanner(input);

It was recommended by javaAdict, honestly I did not understand what it meant, but it did not work.
what i was trying to do is to read a line of integers separated by white space that is entered by the user and and store then into an array of integer as soon as the user hit enter.

Can you post the latest code.

Also you can do this:

Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers separated by space:");

String input = sc.nextLine();

// FOR TESTING YOU CAN TRY THIS:
// String input = "10 20 35 11";

String [] numbers = input.split(" ");
for (int i=0;i<numbers.length;i++) {
   System.out.println("Number: " + numbers[i]);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.