简体   繁体   中英

How do I declare String from result of IF Statement?

I have been playing around and testing out some of the stuff I learned, and this isn't working for me for some reason. It's only mid-app, but I keep running it during development to make not have a thousand problems pile up by the time I'm done. It should be able to run as is though.

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 + ".");
    }
}

This i what I got for output. The launcher class is just literally launching this class, I'm just doing it for good practice. The issue I'm having is trying to label j1 based on answer and use it in my output afterwards.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
j1 cannot be resolved to a variable
at Speed.speedAsker(Speed.java:28)
at Launcher.main(Launcher.java:7)

Thanks in advance.

You declare it outside, and then define it inside the 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.");
}

Declare your string outside the for loop, and assign it inside.

For example:

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 + ".");

Note that Java requires that local variables have definite assignment before they're used. The declaration "String j1" above does not provide a default value, so the else clause must either provide one or exit abnormally.

You can also provide a default value in the declaration:

 String j1 = "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM