0

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();
       }

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

So how should I go about this then because I need to prompt the user to input 4 integers and 4 doubles. Maybe an array is not the best idea?
@MarcusBurkhart do not confuse the indices and the values in the array. What do you think dblNumbers[i] means?
@MarcusBurkhart Your approach was generally correct, but the index of the array is always an int, regardless of the type you need to store in the array. Note how the double is still be read from the Scanner.
0

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();

Comments

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.