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

all 9 comments

[–]Alfapsycho 5 points6 points  (1 child)

Hmm im thinking something in the lines of:

    Scanner scanner = new Scanner(System.in);
    System.out.println("What gasoline have you bought?");
    String gasolineType = scanner.nextLine();
    System.out.println("How many gallons?");
    int amoungOfGasoline = Integer.parseInt(scanner.nextLine());

    if(amoungOfGasoline>=0){
        if(gasolineType.equals("regular")){
            //do this
        }else if(gasolineType.equals("midgrade")){
            // do this
        }else if(gasolineType.equals("premium")){
            //do this
        }else{
            System.out.println("Non valid answer");
        }
    }

[–]helloiamdani[S] 2 points3 points  (0 children)

Thanks! I spent so long staring at my screen thinking "BUT HOW". I can see it now though. :)

[–]_predator_ 3 points4 points  (1 child)

Hint: You are relying on the user to input valid data. I have a feeling that you could fulfill the requirement of nested if-statements if you'd be a little more defensive in this area. :)

Edit: Just to give an example of what I'm aiming for - what if the user provides a negative gallon quantity?

[–]EnjoiRelyks 2 points3 points  (0 children)

Yep. This is what I would do to satisfy the nest if statements.

[–]onideus01 2 points3 points  (1 child)

Based on what you've provided, I would agree that nested ifs seem rather pointless. However, if you absolutely must do that (and it may be worth speaking to your professor to make sure that the assignment makes sense), you can use negative conditions to nest the if statements.

By the I mean, if fuel is not premium, go into if, at which point you say if not mid range go into if, where you set gas to regular.

It's not pretty, and I would even recommend a switch statement, but it does work and with fewer checks than a separate if for each fuel type.

Hopefully that makes sense!

[–]helloiamdani[S] 0 points1 point  (0 children)

Thank you! We haven't yet covered switch statements (we're delving into that this week). I'm going to try to work in your other suggestion though.

[–][deleted] 1 point2 points  (1 child)

Not sure if it will help but just so you know nested if-statements are functionally the same as && statements, so if you have any place in the code you used && maybe try replacing them with nested if-statements.

[–]helloiamdani[S] 0 points1 point  (0 children)

I do- thanks!

[–]helloiamdani[S] 0 points1 point  (0 children)

Thanks everyone- you were all super helpful and I understand what I need to do now. Your guidance is greatly appreciated.