So I have an assignment that requires me to get input from a user and build a table of X's based on an integer they've entered. I'm wanting to add the option to cancel the program if the user enters "C" and to restructure the program into a loop that asks the user to enter an integer or "C" again if they've typed an invalid integer. The assignment asks that the integer from the user be in the range of 1 - 15. I've tried using while, do while, and various if statements, but I'm just not getting something right. I've tried using (columns.equals()) to get the C for cancellation, but that isn't working right either. Thank you for taking the time to help!
import java.util.Scanner;
public class SquareDisplay
{
public static void main(String[] args)
{
int columns;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hey! This program will allow you to enter an integer " +
"value from 1 to 15 and displays a table based on your input.");
System.out.print("Enter an integer value from 1 to 15 or press C to cancel: ");
columns = keyboard.nextInt();
final int rows = columns;
if (columns < 1 || columns > 15)
{
System.out.print("Error! The number you entered is not between 1 " +
"through 15. Please enter an integer from 1 to 15 or press C to cancel: ");
}
if (columns >= 1 && columns <= 15)
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
System.out.print("X");
}
{
System.out.println();
}
}
}
}
This is a common java practice. Normally we'll use
whileloop in this case. Here's the basic format:Don't use
scanner.nextInt(), you don't know what word will user types in. The normal way is to useInteger.parseInt()to parse input string.Besides, your should simply use
ifandelsebecauseif (columns < 1 || columns > 15)has opposite result ofif (columns >= 1 && columns <= 15).