Trying to write a program where it outputs the user entered number if it is between 30 and 70.If not, it should prompt the user to reenter. This is what I have so far, but the code is not running at all.
What should I change?
I tried debugging but it seems like it just gives me random quick fixes that jumble up my original code.
here is the code:
package chpt5_project;
import java.util.Scanner;
public class chpt5_project {
//variables
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count1 = input.nextInt();
while (count1 > 70 || count1 < 30){
System.out.println("Enter a value between 30 and 70: ");
input.close();
}
}
}
CodePudding user response:
Move input.nextInt()
into the while
loop and don't close input
until after the loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count1 = 0;
while (count1 > 70 || count1 < 30){
System.out.print("Enter a value between 30 and 70: ");
count1 = input.nextInt();
}
input.close();
}
CodePudding user response:
// no need to close Scanner for System.in
Scanner scan = new Scanner(System.in);
// create an loop
while (true) {
System.out.print("Enter a value between 30 and 70: ");
int num = scan.nextInt();
// exit the loop if number is correct
if (num > 30 && num < 70)
break;
}