user2789830
user2789830

Reputation: 21

I made my code with an if statement but I need it to reprompt the user to enter a number if they entered an invalid number

I need to make a box of an even number of asterisks from 2-24 and do not know how to reprompt if the wrong number is inputted. the code works perfectly except that it will not reprompt. i tried using a continue statement at the end of the if statement but i have now realized that it will not accept that. is there some other way to get it to reprompt without changing the code?

import java.util.Scanner;

public class Box
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter an even number (2-24): ");
int line = input.nextInt();

if(line < 2 || line > 24 || line % 2 !=0)
    {
    System.out.println("Value must be an even number from 2-24");
 //THE PROBLEM IS THAT I NEED IT TO REPROMPT RIGHT HERE--HELP???
    }
else
{
int j=0;
while(j<line)
    {
    System.out.print("*");
    j++;// j=j+1
    }

System.out.println();       

int k=0;
while(k<line-2)
    {
    System.out.print("*");  
    int c=0;
    while(c<line-2)
        {
        System.out.print(" ");
        c++;
        }
    System.out.println("*");
    k++;
    }

int r=0;
while(r<line)
    {
    System.out.print("*");
    r++;// j=j+1
    }

System.out.println();
}

}

}

Upvotes: 0

Views: 998

Answers (2)

Bohemian
Bohemian

Reputation: 425448

As a curiosity, you can do it as a one-line for loop:

int n;
System.out.print("Enter an even number (2-24): ");
for (n = input.nextInt(); n < 2 || n > 24 || n % 2 !=0; n = input.nextInt())
    System.out.println("Value must be an even number from 2-24\nEnter an even number (2-24): ");

Upvotes: 0

rgettman
rgettman

Reputation: 178363

You need to change your if statement into another while loop. It needs to loop while the line value isn't acceptable. Make sure to re-prompt and re-accept input inside the loop body:

int line = input.nextInt();

while (line < 2 || line > 24 || line % 2 !=0)
{
    System.out.println("Value must be an even number from 2-24");
    //THE PROBLEM IS THAT I NEED IT TO REPROMPT RIGHT HERE--HELP???
    System.out.print("Enter an even number (2-24): ");
    line = input.nextInt();
}

Then you can remove the else part of the now-removed if.

Upvotes: 4

Related Questions