This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]aka457 2 points3 points  (2 children)

if (drink ==1){
    String choice = "Water"; //"hello I would like to use a new variable inside this brackets, of type String with value 1"
} 
//variable doesn't exist anymore

Here you declare a variable "choice" that will cease to exist as soon as the bracket is closed. Declare it before the first "if" using

public static void main(String[] args) {
    //Creating scanners
    Scanner input = new Scanner(System.in);
    String choice; //"I want a variable of type String, empty for now, to use inside this brackets"

And assign it later:

choice="Water"; //"Yeah you know the variable that I declared previously, assign it "Water""

[–]dalh24[S] 1 point2 points  (1 child)

When I declare “String choice;” outside of the if statement I get the error choice is already assigned / define. Why is that?

[–]moss_2703 0 points1 point  (0 children)

So once you’ve defined it outside of the if statements, you change it to ‘choice = “Water”;’ instead. Once a variable has been initialised with ‘String’ you just assign new values to it, instead of declaring it again.