So I keep getting errors similar to this in a few programs and I can't quite figure it out. The array and all variables in the loop are double, so I don't get why it expects an int value. Anyway here it is, all the errors refer to the for statement in the last block:
import java.util.Scanner;
public class Exercise610
{ public static void main (String[] args)
{
int smallest;
Scanner stdIn = new Scanner (System.in);
double array1 [] = new double [100];
for (int i=0; array1[i] != -7; i++)
{
System.out.println("Input a value in yer string, or -7 to end");
array1[i] = stdIn.nextDouble();
}
smallest = indexOfSmallestElement(array1);
System.out.println("The smallest value in the array is " + smallest);
}
public static int indexOfSmallestElement (double[] array)
{
int smallestInt;
double smallest = array[0];
for (double u: array)
{
if (array[u+1] < array[u])
{
smallest = array[u+1];
}
}
smallestInt = (int) smallest;
return smallestInt;
}
}
File: /Users/Crbn/introcs/Exercise610.java [line: 33]
Error: /Users/Crbn/introcs/Exercise610.java:33: possible loss of precision
found : double
required: int
File: /Users/Crbn/introcs/Exercise610.java [line: 33]
Error: /Users/Crbn/introcs/Exercise610.java:33: possible loss of precision
found : double
required: int
File: /Users/Crbn/introcs/Exercise610.java [line: 35]
Error: /Users/Crbn/introcs/Exercise610.java:35: possible loss of precision
found : double
required: int
You cannot say array[u+1]
as this refers to the index of an array. The errors are because u
is a double and the indices in any array are numbers in integers from 0, 1, 2 etc...
You should loop through an array using integers like:
for (int i = 0; i < something; i++){
// do something here
}
You can cast u
to an int if you want (see below code) but better to declare it int
to begin with.
for (double u : array) {
if (array[(int) (u + 1)] < array[(int) u]) {
smallest = array[(int) (u + 1)];
}
}
The reason for the loss of precision error is because an int
occupies 32 bits of memory, a double
occupies 64 bits, so if you try and squeeze a double
into an int
you may lose some data.
I'm not familiar with Java, but I think it could be something to do with this line smallestInt = (int) smallest;
- basically it is letting you know that casting a double
to an int
will result in the loss of data.
I suspect your method is either named wrong or coded wrong, the method name suggests that you should be returning the index, not the value.
smallest = array[u+1];
is assigning the array value, not the array index - this might actually be your problem, you possibly want smallest = u + 1;
given the method name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With