Java中出现了“找不到符号”错误?

3
我正在尝试计算给定单价17和物品数量20的总价格。
public class hw1_task3 {
    public static void main(String[] args) {
        int total = units * price;
        int units = 20;
        int price =  17;
        System.out.printf("The total is: %d", total);
    }    
}

程序出了什么问题?我一直收到一个关于无法找到符号的错误。我很新手,对于Java不是很熟悉,希望能得到帮助。
3个回答

3

您需要将单位和价格移动到总价之上,就像这样:

int price =  17;
int units = 20;
int total = units * price;

2
您在声明变量之前使用了它。以下是这些行的内容:
int units = 20;
int price =  17;

应该首先编写并且

int total = units * price;

之后,正确的行应该是:

int units = 20;
int price =  17;
int total = units * price;

2
在使用变量之前,需要先声明它。在你的程序中,你在变量"units"和"price"被声明之前就使用了它们,因此会收到“找不到符号”的错误提示。要打印变量的值,请使用System.out.println()函数。
public class hw1_task3 {

    public static void main(String[] args) {
        int units = 20;  //Variable declaration and initialization
        int price =  17;  //Variable declaration and initialization
        int total = units * price;
        System.out.println("The total is: "+total);
    }    
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接