Reputation: 13
I'm brand new to Java. At the moment I have been given the problem of casting a 3-by-4 array using a user's input of specific numbers as follows: 2.6 5.1 6 8 5.4 4.4 7 1 9.5 7.9 2 3
Right now, I have got it to work solely for integers, and structured it as such, as I cannot wrap my head around multiple inputs from the user.
What I have if I just use integers (Such as 5 instead of 5.1, and 2, instead of 2.6 etc.) is as follows:
int row, col;
int i, j;
int data[][] = new int[4][3];
col = 3;
row = 4;
Scanner scan = new Scanner(System.in);
// enter array elements.
System.out.println("Enter the provided Array Elements : ");
//Works with integers as input only at the moment.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
data[i][j] = scan.nextInt();
}
}
What I would like is to convert all of the user's input to read as a double data type, and cast the double data types into the array.
Any insight on how to cast them would be greatly appreciated. Thanks!
Upvotes: 1
Views: 290
Reputation: 101
You can't cast arrays in java like you'd probbaly expect. For example, you aren't allowed to do the following operations:
int[] i = new int[0];
double[] d = (double[]) i;
This means, you need to declare your array simply as double[] and replace scan.nextInt()
with scan.nextDouble()
and that's it.
Upvotes: 3