0

我一直在玩耍并测试我学到的一些东西,但由于某种原因这对我不起作用。它只是中间应用程序,但我在开发过程中一直运行它,以免在我完成时堆积一千个问题。它应该能够按原样运行。

import java.util.Scanner;

public class Speed {
    public void speedAsker(){
        Scanner scan = new Scanner(System.in);

        System.out.println("Should we use: 1.KMPH or 2. MPH");
        int s1 = scan.nextInt();
        if(s1==1){
            String j1 = "KMPH";
            System.out.println("We will be using Kilometres for this calculation.");
        }if(s1 ==2){
            String j1 = "MPH";
            System.out.println("We will be using Miles for this calculation.");
        }else{
            System.out.println("That is an invalid input, you must choose between 1 or 2.");
        }
        System.out.println("What speed is your vehicle going in?");
        int d1 = scan.nextInt();
        System.out.println("Your vehicle was going at " + d1 + j1 + ".");
    }
}

这是我得到的输出。启动器类只是从字面上启动这个类,我只是为了良好的实践而这样做。我遇到的问题是尝试根据答案标记 j1,然后在我的输出中使用它。

线程“main”java.lang.Error 中的异常:未解决的编译问题:
j1 无法解析为 Launcher.main(Launcher.java:7)
处 Speed.speedAsker(Speed.java:28)处的变量

提前致谢。

4

2 回答 2

7

你在外面声明它,然后在 if/else 里面定义它

String j1;
if(s1==1){
    j1 = "KMPH";
    System.out.println("We will be using Kilometres for this calculation.");
}if(s1 ==2){
    j1 = "MPH";
    System.out.println("We will be using Miles for this calculation.");
}else{
    j1 = null;
    System.out.println("That is an invalid input, you must choose between 1 or 2.");
}
于 2013-05-28T20:13:23.997 回答
5

在 for 循环之外声明你的字符串,并在里面分配它。

例如:

String j1;

if(s1==1){
    j1 = "KMPH";
    System.out.println("We will be using Kilometres for this calculation.");
}if(s1 ==2){
    j1 = "MPH";
    System.out.println("We will be using Miles for this calculation.");
}else{
    j1 = "";
    System.out.println("That is an invalid input, you must choose between 1 or 2.");
}

...

System.out.println("Your vehicle was going at " + d1 + j1 + ".");

请注意,Java 要求局部变量在使用之前具有明确的赋值。上面的声明“String j1”没有提供默认值,所以else子句必须要么提供一个,要么异常退出。

您还可以在声明中提供默认值:

 String j1 = "";
于 2013-05-28T20:13:01.030 回答