Reputation: 738
Quick question, I found answers close to this but nothing that helps me. I want it to print out a percentage at the end of the code that has 4 numbers after the decimal point, and of course, using an int work work. But using floats gives me an error.
This code:
import java.util.Scanner;
public class HW2johnson_pp4 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("How many numbers will you enter?\n");
float[] numbers = new float[keyboard.nextFloat()];
System.out.printf("Enter " + numbers.length + " integers, one per line:\n");
for (int i = 0; i <= numbers.length - 1; i++) {
numbers[i] = keyboard.nextInt();
}
float sum = 0;
for (int i = 0; i <= numbers.length - 1; i++) {
sum += numbers[i];
}
System.out.printf("The sum is " + sum + "\n");
System.out.printf("The numbers are:\n");
for (int i = 0; i <= numbers.length - 1; i++) {
float perc = (numbers[i] / sum);
float perct = (perc * 100);
System.out.printf(numbers[i] + " which is " + perct + "%% of the sum.\n");
}
}
}
Gives the error:
HW2johnson_pp4.java:8: possible loss of precision
found : float
required: int
float[] numbers = new float[keyboard.nextFloat()];
Upvotes: 0
Views: 1965
Reputation: 11228
You cannot initialize an array with floating point values.
float[] a = new float[4]
And not
float[] a = new float[4.0]
So, The problem is here:
float[] numbers = new float[keyboard.nextFloat()];
Use keyboard.nextInt() instead.
Upvotes: 2
Reputation: 1124
Thats because in line 8 you are making a new array, and passing a float as the length. Since all arrays require an integer as an array length, it will convert the float to an integer, and gives an error. You want to pass in an integer value.
Upvotes: 1
Reputation: 25676
You're using keyboard.nextFloat()
, which is a float, as the length of the array numbers
. The length of an array has to be an int.
Upvotes: 1
Reputation: 98469
You can't create an array of floats whose length is a floating-point value. That is to say, you can't have an array with 2.7 elements.
So the float within the length parameter is getting rounded, causing a loss of precision.
You wanted keyboard.nextInt()
there on line 8, and keyboard.nextFloat()
below on line 13.
Upvotes: 7