1

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.

1 Answer 1

2

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.

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

6 Comments

What does the .split(" ") do? I haven't seen that before.
It splits String into array of Strings based on regular expression taken as parameter.
Is there any way to do this without that? I've yet to learn about that particular bit.
If you want to load everything in one line I do not think so. However using methods for strings is very useful skill.
I will later on have to use some methods for the rest of what I need to do (ex. arithmatic) but this is just giving me a hard time.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.