Reputation: 93
I am trying to ask the user to enter 4 integer values followed by 4 double values. I keep getting the error "possible lossy conversion from double to int". I have tried different things but don't understand the simple conversion. Also.. might there be a better approach to this? Any advice for me is helpful. Eventually I am going to print out the values of these down the road...
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] intNumbers = new int[4];
// Prompt user to enter 4 integer values here
System.out.println("Enter 4 integer numbers below");
// intNumbers only excepts 4 values with the for loop
for (int i = 0; i < 4 && keyboard.hasNextInt(); i++) {
intNumbers[i] = keyboard.nextInt();
}
double[] dblNumbers = new double[4];
// Prompt users to enter 4 double values here
System.out.println("Enter 4 double numbers below");
// dblNumbers only excepts 4 values with the for loop
for (double i = 0; i < 4 && keyboard.hasNextDouble(); i++) {
dblNumbers[i] = keyboard.nextDouble();
}
Upvotes: 0
Views: 268
Reputation: 33
You are using Double in your for-loop, which is not a good idea. Array indexes are always in int, so if you assign a double to it, it will give "possible loss conversion from double to int".
for (int i = 0; i < 4 && keyboard.hasNextDouble(); i++) {
dblNumbers[i] = keyboard.nextDouble();
Upvotes: 0
Reputation: 178253
You should not be using a double
as an index into your array. Always use an int
as an index. Change
for (double i = 0; i < 4 && keyboard.hasNextDouble(); i++) {
dblNumbers[i] = keyboard.nextDouble();
}
to
// vvv
for (int i = 0; i < 4 && keyboard.hasNextDouble(); i++) {
dblNumbers[i] = keyboard.nextDouble();
}
Upvotes: 3