Home > Blockchain >  How to remove repetitive operations in a separate method?
How to remove repetitive operations in a separate method?

Time:02-11

My code has to guess the hidden number from 0 to 100 in 7 attempts. And every time I need to call the same operations again. How can I move these operations into a separate method and call them from there?

public class Main {
  public static void main(String[] args) throws IOException {
    int min = 0;
    int max = 100;
    int midrange = Math.round((min   max)/2);
    String strInput = "";
    Scanner scan = new Scanner(System.in);

    while (!strInput.equals("1")){
        System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
        strInput = scan.nextLine();
    }

    while (!strInput.equals(" ") && !strInput.equals("-") && !strInput.equals("=")){
        System.out.println("Is this number greater than, less than or equal to "   midrange   "? "  
                "Enter ' ', if it's greater, '-' if it's less and '=' if it's equal:");
        strInput = scan.nextLine();
    }

    if (strInput.equals("=")) System.out.println("Great! Thank you for the game.");
    else if (strInput.equals(" ")){
        // reduce the range
        min = midrange;

        // find a new midrange
        midrange = Math.round((min   max)/2);
    } else if (strInput.equals("-")){
        max = midrange;
        midrange = Math.round((min   max)/2);
    }

    strInput = "";

    while (!strInput.equals(" ") && !strInput.equals("-") && !strInput.equals("=")){
        System.out.println("Is this number greater than, less than or equal to "   midrange   "? ");
        strInput = scan.nextLine();
    }

    // ... and so on until the correct number is found.

  }
}

CodePudding user response:

You don't need multiple while loops. Just check for equality and put your if-else-block into the while loop. If you guessed the number correct just break out of the loop.

public static void main(String[] args) throws IOException {

    int min = 0;
    int max = 100;
    int midrange = Math.round((min   max) / 2);
    String strInput = "";
    Scanner scan = new Scanner(System.in);

    System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
    strInput = scan.nextLine();

    while (!strInput.equals("=")) {
        System.out.println("Is this number greater than, less than or equal to "   midrange   "? "  
                "Enter ' ', if it's greater, '-' if it's less and '=' if it's equal:");
        strInput = scan.nextLine();
        if (strInput.equals("=")) {
            System.out.println("Great! Thank you for the game.");
            break;
        } else if (strInput.equals(" ")) {
            min = midrange;
            midrange = Math.round((min   max) / 2);
        } else if (strInput.equals("-")) {
            max = midrange;
            midrange = Math.round((min   max) / 2);
        }
    }
}
  • Related