221k views
4 votes
JAVA

How can I make the program repeat the loop automatically if the user enters a wrong value or a negative value?

TYPED CODE :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int value, result=0;
System.out.print("Enter a integer value: ");
value = input.nextInt();
if (value<=0){
System.out.print("ERROR, Please Enter a positive integer value");
return;
}
for(int i = 1; i <= value; i++){
result +=i;
}
System.out.print("The sum of integers is: " + result);
}
}

JAVA How can I make the program repeat the loop automatically if the user enters a-example-1
JAVA How can I make the program repeat the loop automatically if the user enters a-example-1
JAVA How can I make the program repeat the loop automatically if the user enters a-example-2
JAVA How can I make the program repeat the loop automatically if the user enters a-example-3

1 Answer

2 votes

Answer:

To repeat the loop automatically if the user enters a wrong value or a negative value, you can use a 'while' loop to continuously prompt the user for input until they enter a valid positive integer.

Code:

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int value, result = 0;

boolean valid = false;

while (!valid) {

System.out.print("Enter a positive integer value: ");

value = input.nextInt();

if (value <= 0) {

System.out.println("ERROR: Please enter a positive integer value.");

} else {

valid = true;

for (int i = 1; i <= value; i++) {

result += i;

}

System.out.println("The sum of integers is: " + result);

}

}

}

}

JAVA How can I make the program repeat the loop automatically if the user enters a-example-1
User Lalaluka
by
6.7k points