【问题标题】:Unexpected type error with multiplication of two integers in a while loop在 while 循环中将两个整数相乘时出现意外的类型错误
【发布时间】:2017-12-05 18:44:48
【问题描述】:

我应该在我的程序中实现一个方法,将区间 n1,n2 中的所有整数相乘。这是我的代码:

static int productofIntervall (int n1, int n2){
    int a;
    while(n1 <= n2){
        n1*n2 = a;
        n1=n1++;
    }
    return(a);
}   
        public static void main(String[] args){
        System.out.println(productofIntervall(6,11));
    }

}

当我尝试遵守时,我收到了错误:

Main.java:6: error: unexpected type
                        (n1)*(n2)=a;
                            ^
  required: variable
  found:    value
1 error

谁能告诉我怎么了? 提前致谢。

【问题讨论】:

  • 语句的写法是你试图将a分配给n1 * n2。另外,n1 = n1++ 的赋值也不是你想的那样。
  • 这看起来更像是有一个测试来识别编译错误。所以最好你学习java,直到你自己弄清楚这个。 PS:您可以尝试使用 Eclipse 之类的 IDE,这样可以节省一些时间,因为它会在保存时编译。
  • 有一个类似的问题here

标签: java compiler-errors


【解决方案1】:

您需要初始化a = 0 并设置a = n1*n2,而不是相反。 n1 = n1++ 也可以并且最好只替换为 n1++

您基本上是将两个数字的乘积设置为一个不起作用的值(未初始化的变量)

【讨论】:

    【解决方案2】:

    给定以下代码:

    package com.example.so.questions;
    
    public class SO47660627CompilationAndIncrement {
    
        public static void main(String[] args) {
    
            int a = 0;
            int b = 1;
            int c = 0;
            int d = 1;
            int e = 0;
            int f = 0;
            int g = 1;
            int h = 1;
            int i = 0;
            int j = 0;
    
            a = b++;
            c = ++d;
            e = e++;
            f = ++f;
            i = g-(g++);
            j = h-(++h);
    
            System.out.println(" int a=0; b=1; a=b++ // a is : "+a+" and b is : "+b);
            System.out.println(" int c=0; d=1; c=++d // c is : "+c+" and d is : "+d);
            System.out.println(" int e=0; e = e++ ; // e is : "+e);
            System.out.println(" int f=0; f = ++f ; // f is : "+f);
            System.out.println(" int g=1; int i = g-(g++); // i is : "+ i);
            System.out.println(" int h=1; int j = h-(++h); // j is : "+ j);
    
        }
    
    }
    

    如果您运行 FindBugs 源代码分析器,它会标记为一个问题 - 包含以下内容的行:

    e = e++;
    

    解释是:

    错误:覆盖增量 com.example.so.questions.SO47660627CompilationAndIncrement.main(String[])

    代码执行递增操作(例如,i++),然后 立即覆盖它。例如,i = i++ 立即覆盖 与原始值的增量值。

    运行上述代码,输出为:

     int a=0; b=1; a=b++ // a is : 1 and b is : 2
     int c=0; d=1; c=++d // c is : 2 and d is : 2
     int e=0; e = e++ ; // e is : 0
     int f=0; f = ++f ; // f is : 1
     int g=1; int i = g-(g++); // i is : 0
     int h=1; int j = h-(++h); // j is : -1
    

    从上面的输出中,我们可以得出结论,后自增操作或预自增操作涉及创建一个存储原始值的临时变量 - 在后自增操作的情况下是在自增操作之前,在自增操作的情况下是在自增操作之后预递增操作,然后将存储在临时变量中的结果进一步应用到表达式中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多