Reputation: 345
Alright, so I want to store values in an array. Here is my code :
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner bob = new Scanner(System.in);
double[] mylist;
System.out.println("What is your first value?");
mylist = bob.nextDouble();
System.out.println("What is your second value?");
mylist = bob.nextDouble();
}
}
Issue #1: I'm being told mylist = bob.nextDouble()
should be nextLine()
. Why is that if it is clearly a double?
Goal: I want to somehow store those values given into an array so that I could later pull them out. Can anyone help?
UPDATE
For Issue #1, it tells me that it cannot convert from Double()
to Double[]
. What does this mean?
Upvotes: 3
Views: 45411
Reputation: 1737
Better still, use a list with generics.
List<Double> myList;
myList.add(bob.nextDouble());
That way, you can add as many doubles you want to the list. So that you dont have to worry about the indexing.
Upvotes: 0
Reputation: 68715
The error is because you are trying to assign a double value to array in the following statement:
mylist = bob.nextDouble();
as mylist is defined as an array here:
double[] mylist;
First you need to intialize your array:
double[] mylist = new double[2]; // initialise array to have two elements
and then try to assign the array elements with the user input like this:
mylist[0] = bob.nextDouble();
mylist[1] = bob.nextDouble();
Upvotes: 5
Reputation: 8746
mylist
is an array
of doubles, not a single double
.
When you do mylist = bob.nextDouble();
you are basically trying to make an entire array equal a single number.
You instead need to assign the number to a specific place in the array.
Initialize the array with the amount of elements you are going to store in the array:
double[] mylist = new double[2];
Assign the double to a specific place in the array:
mylist[0] = bob.nextDouble();
mylist[1] = bob.nextDouble();
Upvotes: 3
Reputation: 25960
An array is not a double, you need to select an index :
double[] arr = new double[2];
System.out.println("What is your first value?");
arr[0] = bob.nextDouble();
System.out.println("What is your second value?");
arr[1] = bob.nextDouble();
Also, don't call an array a list, use CamelCase for naming your variables/methods/classes, and initialize the array. I recommend you reading a Java tutorial for working on the basics of the language.
Upvotes: 3
Reputation: 201467
It's an array (which is a type of object). First, create an array large enough to store your double
(s) (not int
(s)). And store the values at appropriate indices. Something like,
Scanner bob = new Scanner(System.in);
double[] mylist = new double[2];
System.out.println("What is your first value?");
mylist[0] = bob.nextDouble();
System.out.println("What is your second value?");
mylist[1] = bob.nextDouble();
System.out.println(Arrays.toString(mylist));
Upvotes: 3