二元运算符'<=','+='的错误操作数类型

我不明白为什么我的二进制操作数不适用于 if 语句。例如,我收到错误,二元运算符“<=”的错误操作数类型。第一种:double[] 第二种:double for if(prices <=5.00)

public class Prices2
{
public static void main (String[] args)
{
double[] prices = {2.45, 7.85, 1.35, 1.55, 4.05, 9.55, 4.55, 1.45, 7.85, 1.25, 5.55, 10.95, 8.55,
2.85, 11.05, 1.95, 5.05, 8.15, 10.55, 1.05};
double average;
double total = 0.0;
int i;
for (i = 0; i < 20; i++)
{
total += prices;
}

System.out.println("Sum of all prices: "+total+"n" );
for (i = 0; i < 20; i++)
{
if (prices <= 5.00){
System.out.println(prices + " is less than $5.00");
}
}
average = total / (20);
System.out.println("nThe average price is " + average + "n");
for (i = 0; i < 20; i++)
{
if (prices >= average) {
System.out.println( " Values above average: " + prices);
}
}
}
}

回答

由于价格是一个数组 (double[]) 并且 5.00 是一个单双,因此检查“价格 <= 5.00”是没有意义的。这就像说“如果 [1.2, 3.4, 5.7, 6.2, 3.4] < 5.00”。所以编译器会用这种措辞抱怨。

更新 3/18 每个后续问题:

简短的回答是用价格 [i] 变量替换价格变量以匹配检查每个点的迭代,因为这似乎是计算的目标。此外,您不需要在顶层声明“i”。您可以在每个 for 循环中执行此操作,这样一个循环就不会意外地影响另一个循环。

public class Prices {
    public static void main(String[] args) {

        // Set up a list of TEST prices to check for various conditions
        double[] prices = { 2.45, 7.85, 1.35, 1.55, 4.05, 9.55, 4.55, 1.45, 7.85, 1.25, 5.55, 10.95, 8.55,
                2.85, 11.05, 1.95, 5.05, 8.15, 10.55, 1.05 };
        
        int numberOfPrices = prices.length;
        
        // GOAL: Calculate Sum of all numbers
        // For each price (i=0, 1, 2... 19), add THAT price to the current value of total
        double total = 0.0;
        for (int i = 0; i < numberOfPrices; i++) {
            total += prices[i];
        }
        System.out.println("Sum of all prices: " + total + "n");
        
        // GOAL: Check for for those less than 5
        // For each price (i=0, 1, 2... 19), see if THAT price is less than 5.00
        for (int i = 0; i < numberOfPrices; i++) {
            if (prices[i] <= 5.00) {
                System.out.println(prices[i] + " is less than $5.00");
            }
        }
        
        // Calculate the average price (without hard-coding)
        double average;
        // average = total / (20);
        average = total / numberOfPrices;
        System.out.println("nThe average price is " + average + "n");
        
        // GOAL: Check for Above Average numbers
        // For each price (i=0, 1, 2... 19), see if THAT price is above the average we computed before
        for (int i = 0; i < numberOfPrices; i++) {
            if (prices[i] >= average) {
                System.out.println(" Values above average: " + prices[i]);
            }
        }
    }
}


以上是二元运算符'&lt;=','+='的错误操作数类型的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>