You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组操作中遭遇"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 i as a double, but array indices in Java have to be integers (int type). When you try to use i (a double) to access weights[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:

  1. Uses an int loop variable i to safely access each array element by index
  2. The if condition now checks for elements that are either ≤100 or ≥200 (exactly the ones you want to print)
  3. Prints the element weights[i] instead of the index i

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 int for array loop indices in Java
  • Make sure your if condition 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 09:34:31