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?
>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");
}
}