首页 > 解决方案 > 无法解析为 Java 中的变量

问题描述

我在 Java 中遇到了这个问题。当我运行程序时,它给了我错误:variable_name 无法解析为变量。

if(name.equalsIgnoreCase("...")) {
    System.out.print("...");
    float name1=SIn.readFloat();
} else if(name.equalsIgnoreCase("...")){
    System.out.print("...");
    float name2=SIn.readFloat();
}
try {
    float converted=name1*valueget;    //the error is here with the variable 'name'
    System.out.println(...);
}

标签: java

解决方案


答案很简单,您正在尝试使用不存在的变量。我们只是说, first if returns false, then 变量name1永远不会初始化。

if(name.equalsIgnoreCase("...")) {    // doesn't equal
    System.out.print("...");
    float name1 = SIn.readFloat();    // not initialized
} else if(name.equalsIgnoreCase("...")){
    System.out.print("...");
    float name2 = SIn.readFloat();
}
try {
    float converted = name1 * valueget;    // using non-existing variable
    System.out.println(...);
}

您应该做的是,在该语句之前声明一个变量if-else并在if-else.

float floatName = 0;   // set it up as zero, because you don't have else statement
if(name.equalsIgnoreCase("...")) {
    System.out.print("...");
    floatName = SIn.readFloat();
} else if(name.equalsIgnoreCase("...")){
    System.out.print("...");
    floatName = SIn.readFloat();
}
try {
    float converted = floatName * valueget;
    System.out.println(...);
}

推荐阅读