我一直在玩并测试我学到的一些东西,但由于某种原因,这对我不起作用.它只是mid-app,但是我在开发过程中继续运行它,以便在我完成时不会有一千个问题堆积起来.它应该能够按原样运行.
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
中的Speed.speedAsker(Speed.java:28)
中的变量(Launcher.java: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."); }
在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 = "";