Home > database >  How do I stop if statement after the first true return value?
How do I stop if statement after the first true return value?

Time:07-09

this code should print out a reply based on user input, user is given 3 tries to enter input after invalid tries. It works when they return all invalid values but code still asks for user input after they have answered yes or no.

'''

import java.util.*;
public class Equality{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Do you have a job?(yes/no): ");
        String response = input.next();
        if(response.equalsIgnoreCase("yes")){
        System.out.println("You are the breadwinner!");
        }
        else if(response.equalsIgnoreCase("no")){
        System.out.println("Keep trying, you will find one!");
    }
    else {
        System.out.println("Invalid Entry! Try again!");
    }
    response = input.next();
    if(response.equalsIgnoreCase("yes")){
            System.out.println("You are the breadwinner!");
    }
    else if(response.equalsIgnoreCase("no")){
        System.out.println("Keep trying, you will find one!");
    }
    else {
        System.out.println("Invalid Entry! Try again!");
    }
    response = input.next();
    if(response.equalsIgnoreCase("yes")){
        System.out.println("You are the breadwinner!");
    }
    else if(response.equalsIgnoreCase("no")){
        System.out.println("Keep trying, you will find one!");
    }
    else {
        System.out.println("Too many invalid entries!");
    }
}
}

'''

thank you.

CodePudding user response:

you really should have a look at loops (and how to escape them)! It could end up something like that: (pseudo-code)

boolean valid = false;
int counter = 0;
while(!valid && counter < 3) {
  if ("yes") {
   ...
   valid = true;
  } else if ("no") {
    ...
   valid = true;
 } else {
   counter  :
 }
}

CodePudding user response:

You dont need to repeat it. You can either use a while loop or a for loop. Here is a sample

import java.util.Scanner;

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

        for (int i = 0; i <= 2; i  ) {
            System.out.println("Do you have a job? (Yes/No): ");
            String response = input.next();
            if (response.equalsIgnoreCase("Yes")) {
                System.out.println("You are the breadWinner");
                break;   //will exit it out of the loop
            }
            else if (response.equalsIgnoreCase("No")){
                System.out.println("Keep, trying you will find one!");
            }
            else {
                System.out.println("Invalid Value, Try again!");
            }
        }
    }
}

CodePudding user response:

Because you have multiple if statements, you can't break away from the latter 2 if the first one is answered correctly. Regardless of the first if() { } statement's results, the following code and onwards will always be called.

(Your code)

if(response.equalsIgnoreCase("yes")){
  System.out.println("You are the breadwinner!");
} else if(response.equalsIgnoreCase("no")){
  System.out.println("Keep trying, you will find one!");
} else {
  System.out.println("Invalid Entry! Try again!");
}

//this following code will always be run after your first if statement!
response = input.next();
if(response.equalsIgnoreCase("yes")){
  System.out.println("You are the breadwinner!");
}
...

Probably the best way to do what you're trying to accomplish is by working with loops. Here is a good tutorial on how while loops in Java work. That tutorial should aid in understanding the following (improved) code, which:

  • Exits loop as soon as the user gets it correct
  • Allows a maximum of 3 attempts

(New code)

import java.util.*;
public class Equality {
  public static void main(String[] args) {

    //this int will be increased by 1 everytime the code completes
    int attempts = 0;

    //while attempts < 3, all of the following code will be executed
    //after it is completed, it will be run again! until attempts >= 3
    while(attempts < 3) {
      Scanner input = new Scanner(System.in);
      System.out.println("Do you have a job?(yes/no): ");
      String response = input.next();

      // Determine the User's response
      if(response.equalsIgnoreCase("yes")) {
        System.out.println("You are the breadwinner!");
        break; // 'break' is a keyword used to BREAK out of the loop = stop!
      }
      else if(response.equalsIgnoreCase("no")) {
        System.out.println("Keep trying, you will find one!");
      }
      else {
        System.out.println("Invalid Entry! Try again!");
      }
      attempts  ; //this is a fancy line for entries = entries   1

      //After their last attempt, system will print a warning
      if(attempts >= 3) {
        System.out.println("No More Remaining Attempts!");
        //notice how we dont need a break statement here!
        //this is because on the next iteration (loop) of the loop,
        //attempts = 3, and while (attempts < 3) is no longer true! = no loop
      }
    }
  }
}

Hope this helps! This is also my first Stack Overflow Answer so I apologise for any formatting/technical issues :D

CodePudding user response:

You won't need to repeat typing the code. Instead let's use a while loop. This code will continue to run until the using has had 3 tries. At the very bottom is where we will add to the integer variable entries by one only if we make it to the end.

The reason the code is not stopping is because you haven't told it to stop. Once you reach a stopping point in the loop, you can use this break statement to exit the while loop.

If the user ever gets 3 entries (or more) the system will reply with too many entries


import java.util.*;
public class Equality {
  public static void main(String[] args) {
    int entries = 0;
    while(entries < 3) {

      // Get the User's response
      Scanner input = new Scanner(System.in);
      System.out.println("Do you have a job?(yes/no): ");
      String response = input.next();

      // Determine the response from System
      if(response.equalsIgnoreCase("yes")) {
        System.out.println("You are the breadwinner!");
        break; // this will stop the while loop
      }
      else if(response.equalsIgnoreCase("no")) {
        System.out.println("Keep trying, you will find one!");
      }
      else {
        System.out.println("Invalid Entry! Try again!");
      }
      entries  ;

      // Let the user know they have had too many entries
      if(entries >= 3) {
        System.out.println("Too many invalid entries");
      }
    }
  }
}

Here are some resources to the new things I added to your code

The while loop: https://www.w3schools.com/java/java_while_loop.asp

The break statement: https://www.geeksforgeeks.org/break-statement-in-java/

  • Related