[Solved] Setting limitation for running a while loop in java [closed]


I recommend you use do-while loop (it doesn’t mean you can’t solve it using other types of loop) because it will make the code easy to understand. A do-while loop guarantees that its body will be executed at least once.

You also need a variable, e.g. int attempts to track the number of attempts.

Do it as follows:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int numl = readNumber("Number1: ", 1, 10);
        int num2 = readNumber("Number2: ", 11, 20);
        int add = Total(numl + num2);
    }

    public static int readNumber(String Prompt, int min, int max) {
        int value;
        int attempts = 0;
        Scanner scanner = new Scanner(System.in);
        do {
            System.out.print(Prompt);
            value = scanner.nextInt();
            if ((value >= min && value <= max)) {
                break;
            }
            attempts++;
        } while (attempts < 3);

        if (attempts == 3) {
            // Reset `value`
            value = 0;
        }

        return value;
    }

    public static int Total(int sum) {
        System.out.println("SUM = " + sum);
        return sum;
    }
}

A sample run:

Number1: 10
Number2: 15
SUM = 25

Another sample run:

Number1: 50
Number1: 56
Number1: -1
Number2: 23
Number2: -60
Number2: 50
SUM = 0

Given below is the code using while loop instead of a do-while loop:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int numl = readNumber("Number1: ", 1, 10);
        int num2 = readNumber("Number2: ", 11, 20);
        int add = Total(numl + num2);
    }

    public static int readNumber(String Prompt, int min, int max) {
        int value;
        int attempts = 0;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            if (attempts == 3) {
                // Reset `value`
                value = 0;
                break;
            }
            System.out.print(Prompt);
            value = scanner.nextInt();
            if ((value >= min && value <= max)) {
                break;
            }
            attempts++;
        }

        return value;
    }

    public static int Total(int sum) {
        System.out.println("SUM = " + sum);
        return sum;
    }
}

3

solved Setting limitation for running a while loop in java [closed]