如何从IF语句的结果声明String?

时间:2013-05-28 20:11:35

标签: java string if-statement

我一直在玩并测试我学到的一些东西,但由于某种原因,这对我来说并不适合。它只是应用程序的中间版本,但我在开发过程中一直运行它,以便在我完成之前不会有一千个问题堆积起来。它应该能够按原样运行。

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无法解析为变量
          在Speed.speedAsker(Speed.java:28)
          在Launcher.main(Launcher.java:7)

提前致谢。

2 个答案:

答案 0 :(得分: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.");
}

答案 1 :(得分: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 = "";