Reputation: 13
So, I want to ask the user to input three values (all double) with only one prompt and have them stored in an array (I just started getting familiar with creating objects and arrays). This is what I've got so far:
import java.util.Scanner;
final int ARRAY_LIMIT=3;
Scanner input=new Scanner(System.in);
System.out.println("Enter the points and speed: ");
double entryVal=input.nextDouble();
double[] array=new double[ARRAY_LIMIT];
for(int entriesCounter=0; entriesCounter<array.length; entriesCounter++)
{
array[entriesCounter]=entryVal;
if(array[2]==0)
break;
}
So when I try to run it and I input something like 1.0, 1.0, 10.0, but I get all sorts of code spewed out. The point is to input all 3 values at the same time, eventually use these values in separate equations and terminate if the third number is 0. But I want to first be able to get these values to be stored correctly. I've tried to look at other previously answered questions but couldn't find something that helped me. I'm very new to Java so I'm still bumbling about. Any detailed help would be greatly appreciated.
Upvotes: 1
Views: 1757
Reputation: 23049
The best way I think is just read the whole line to String :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the points and speed: ");
String entryVal = input.nextLine();
String[] stringArray = entryVal.split(" ");
double[] array = new double[stringArray.length];
for (int i = 0; i < array.length; i++) {
array[i] = Double.valueOf(stringArray[i]);
}
}
Note that each value has to be seperated only by space.
Upvotes: 2