user2868900
user2868900

Reputation: 781

JAVA If else process that quits if user input 1 is = 0, doesn't work

I am very new to Java and I'm trying to get a small code to work, but I get the message "The local variable tal2 may not be defined". I see the issue, but I'm not really sure how to solve it.

The program is supposed to print the line "Thank you" if the first input is 0, else let the user proceed to input #2 and then run the second else if statement.

    public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);

    int tal1;
    int tal2; 

    tal1 = stdIn.nextInt();
    if (tal1 == 0 ) {
        System.out.println("Thank you.");
    } else {
    tal2 = stdIn.nextInt();
    }

    if (tal1 > tal2) {
            System.out.println(tal1 + " is greater than " + tal2); 
    } else {
        System.out.println(tal2 + " is greater than " + tal1);
    }

    }

Upvotes: 0

Views: 99

Answers (5)

dinesh.kumar
dinesh.kumar

Reputation: 168

because second input statement is inside first else block. So if you will enter 0 as first input so then first else bock will not be executed and it will not ask for input second time and will go to the else bock of second if. so put second input statement out of first if-else block.

Upvotes: 0

AsSiDe
AsSiDe

Reputation: 1846

Change your declaration of tal2 to:

int tal2=0;

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201507

You didn't call System.exit() like you probably meant to.

if (tal1 == 0) {
  System.out.println("Thank you.");
  System.exit(0);
}

You might also just return;

Alternatively, you might move your other statements into your first else block

} else {
  tal2 = stdIn.nextInt();
  if (tal1 > tal2) {
    System.out.println(tal1 + " is greater than " + tal2); 
  } else {
    System.out.println(tal2 + " is greater than " + tal1);
  }
}

Upvotes: 4

Chi Zhang
Chi Zhang

Reputation: 1

Change line 4 of your code to the following int tal2 =-100;

Upvotes: 0

deejay
deejay

Reputation: 575

Initialize your variables, as these are local variables ant it should always be intialized.

int tal1 = 0;
int tal2 = 0;

You need to call System.exit(0), if you want to exit from the system.

Upvotes: 0

Related Questions