question about getting data from the console
I'm trying to fill an arraylist with number but I don't want the user to have to press enter after each number. I would like it if they could put all the numbers on one line separated by white space like so.
Enter initial candy counts: 23 32 43 5 6 54
here what I have so far.
also if anyone can point me in the right direction about how to end the loop after they press enter would be much appreciated.
thank you.
Code :
Scanner userInput = new Scanner(System.in);
ArrayList<Integer> candy = new ArrayList<Integer>();
int numCandy = 0;
while() {
System.out.println("Enter initial candy counts: ");
numCandy = userInput.nextInt();
candy.add(numCandy);
}
Re: question about getting data from the console
What happens when you compile and execute the code and enter the data that way?
The Scanner class has methods to test if there is input ready to read. The method names start with has
Or you could use the nextLine() method to read all of one line into a String and use a Scanner with that String or use the String class's split() method to get the data.
Re: question about getting data from the console
Thanks for the idea. But now i cant figure out why the numbers are still strings. any ideas
Code :
Scanner userInput = new Scanner(System.in);
ArrayList<Integer> candy = new ArrayList<Integer>();
String temp;
String[] candyNum;
System.out.print("Enter initial candy counts: ");
temp = userInput.nextLine();
candyNum = temp.split(" ");
for (int i = 0; i < candyNum.length; i++) {
candy.add(Integer.parseInt(candyNum[i]));
}
Re: question about getting data from the console
Quote:
why the numbers are still strings
Can you explain what numbers you are talking about? What variable hold the Strings? Where and how would they have been changed to something else?
Re: question about getting data from the console
I thought Integer.parseInt(candyNum[i]) would change the string to a int?
Re: question about getting data from the console
Why do you think it is not doing that?
Re: question about getting data from the console
API parseInt: "Parses the string argument as a signed decimal integer"
Re: question about getting data from the console
What is your question or problem?
Re: question about getting data from the console
OMG i'm so sorry i must of made a mistake when i was testing it. everything works fine thanks for all your help.
Re: question about getting data from the console
Glad you got it worked out.