Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a loop in Java that doesnt stop until user inputs the correct number (beginner)

So, I started learning Java for class a couple days ago, and I’m getting used to everything.
I was practicing and tried to write a code that asks for a number higher than 0. The problem is, I don’t know how to make it so when the user inputs a invalid number the loop restarts and the user can input another number in the console. Been searching on the internet for a couple hours, tried the while loops and booleans but I only managed to create an infinite loop and couldn’t fully understand all the intermediate solutions.

This is the basic code I wrote:

import java.util.Scanner;

public class Prueba {
    public static void main(String[] args) {
        Scanner userNumber=new Scanner(System.in);
        System.out.println("Write a number higher than 0");
        double number=userNumber.nextDouble();
        if(number<=0) {
            System.out.println("You need to write a valid number");
        } else {
            System.out.println("Congratulations, you wrote a valid number");
        }
    }
}

Could anyone explain in beginner terms how could I do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The concept you’re asking about is called a loop. Loops, allow a certain piece of code to execute multiple times until a given condition is met.

In this case, the loop should execute until the condition of: "valid input", is met.

Creating a boolean variable (Boolean indicates either true or false) to check whether the the condition has been met will solve this issue.

boolean conditionMet = false;
    while (conditionMet == false) {
        Scanner userNumber=new Scanner(System.in);
        System.out.println("Write a number higher than 0");
        double number=userNumber.nextDouble();
        if(number<=0) {
            System.out.println("You need to write a valid number");
        } else {
            conditionMet = true;
            System.out.println("Congratulations, you wrote a valid number");
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading