数组操作中遭遇"incompatible types possible lossy conversion from double to int"错误的解决求助
数组操作中遭遇"incompatible types possible lossy conversion from double to int"错误的解决求助
Hey there! Let's work through this issue together, it's a common small snag with Java arrays, so no worries 😊
First, let's break down why you're getting that error:
- You declared your loop variable
ias adouble, but array indices in Java have to be integers (int type). When you try to usei(a double) to accessweights[i], Java complains because converting a double to an int can lose precision (like if i was 1.5, it can't be a valid array index). That's exactly what the "possible lossy conversion" error is talking about.
Next, let's fix the code to match your goal: you want to print all numbers in the array that are not between 100 and 200 (so ≤100 or ≥200), and you were accidentally trying to print the index i instead of the actual array element weights[i].
Here's the corrected code:
double[] weights = {98.3, 108.5, 154.9, 210.0, 175.6, 99.9, 100.1}; // Change loop variable to int since array indices are integers for(int i = 0; i < weights.length; i++){ // Reverse the condition: check if element is NOT in 100-200 range if(weights[i] <= 100 || weights[i] >= 200){ // Print the actual array element, not the index System.out.println(weights[i]); } }
Let's check what this does:
- Uses an
intloop variableito safely access each array element by index - The
ifcondition now checks for elements that are either ≤100 or ≥200 (exactly the ones you want to print) - Prints the element
weights[i]instead of the indexi
When you run this code, it will output exactly what you wanted:
98.3 210.0 99.9
Just to recap the key fixes:
- Always use
intfor array loop indices in Java - Make sure your
ifcondition matches your actual goal (reversing the range check here) - Print the array element itself, not the index, when you want to output the value
备注:内容来源于stack exchange,提问作者user29603034
相关产品推荐
相关产品推荐

