**Thanks Adi219 & Charles Spencer for helping with my part 1.
Now i'm trying a different approach, by validating the input before it store into an array, it look fine most of the time, but the exception only run once.
This is what i input to test the validating
1) I input "a", it returned "enter number between 0 to 100" which is correct.
2) I input 1000, and it returned "Invalid age" which i can tell that my IF conditions works.
3) No issue when i input the correct value for User no.1
Problem happens when i try to run the same test on User no.2. After I input correct value for User no.1, I type in "A" again and the programs just bypass all those conditions and captured no integer value.
import java.util.Scanner;
public class test2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = 0;
double x = 0;
double Total = 0;
double Average = 0;
int Users = 2; //I fixed a number for testing purpose
boolean isNumber =false;
double ages[] = new double[Users];
for(int counter =0; counter < Users; counter++){
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x =input.nextDouble();
if(x<0 || x>100){
System.out.print("Invalid age.. try again.. ");
}else if(x>0 || x<100){isNumber=true;}
}catch(Exception e){
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
System.out.println("User Age is "+ x); //Just to check input user's age
}
}
}
Because your entire do/while loop is based on whether isNumber is false, if you enter a valid number for user1, the isNumber variable is set to true, and the do/while loop will never run again because you never set isNumber back to false. There are two places were I set isNumber back to false, I've marked them. But I'm pretty sure this whole thing should be rewritten. For example there's no need to do:
else if(x > 0 || x < 100)
because you've already done:
if(x<0 || x>100)
If you do the first condition as x <= 0 || x >= 100 there's no need to do an else if statement.
for(int counter = 0; counter < Users; counter++)
{
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x = input.nextDouble();
if(x<0 || x>100)
{
isNumber = false; // Set to false if invalid number
System.out.print("Invalid age.. try again.. ");
}
else if(x > 0 || x < 100)
{isNumber = true;} // If the age for user1 is valid, isNumber is set
// to true
}catch(Exception e)
{
isNumber = false; // Set to false if number invalid
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
Related
I'm trying to make it so that when the user enters anything but y/n it'll say error and when they enter n it'll say have a great day. This is what I have so far, but I keep running into trouble.
This is the assignment:
Write a program that gets an integer from the user, say x, and then
prints an x by x square, and it prints that square x number of times.
For example, if the user enters 4, your program will print a 4x4
square four distinct times. Specifics:
The user enters a value 3-15. Input validation: only accept 3-15.
Allow the user to repeat the program if desired. Input validation: Y
or N only, but also allow lowercase entries.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
char answer = 'y';
while (answer == 'y' || answer == 'Y') {
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
}
answer = 'n';
while (answer == 'n' || answer == 'N') {
System.out.println("Program ending. Have a great day.");
}
keyboard.close();
}
}
You can solve this problem by only using one while loop. You use a break condition to inidicate that the loop should terminate (in your example if the user enters 'n').
Here is an example how I would try to solve this problem:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
boolean exit = false; // define the boolean variable
char answer = 'y';
while (!(exit)) { // start the while loop
if (answer == 'y' || answer == 'Y') { // if the user enters 'y' proceed with your code
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
} else if (answer == 'n' || answer == 'N') { // if the user enters 'n' exit the program and the loop
System.out.println("Program ending. Have a great day.");
exit = true;
} else { // display an error message when something else is typed
System.out.println("You entered an unvalid char, please answer by saying Y/N!");
answer = keyboard.next().charAt(0);
}
}
System.out.println("Reached end of program!");
keyboard.close();
}
Since this looks like homework I won't post the full answer but you can change the
while (answer == 'n' || answer == 'N')
to
if (answer == 'n' || answer == 'N')
Also close the scanner inside the if block above. The else case to the above is where you would throw the error. Hope its clear.
EDIT
Another thing I would like to add is that you can remove answer = 'n'; before the if condition above. That will already be read by
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
Hello all I am trying to validate a set of inputs from a user, where it does not accept blanks, letter, letter with numbers, and numbers out of the range 0=100.
It goes fine except but when I input greater than 100, for example 150, it will catch and tell you to try again but when a letter is typed on the second prompt, it fails. And it'll only fail if the sequence of input is int is greater than 100 is input and the second input is a letter. I have a feeling it is the logic but I cant figure out exactly on which part.
It errors right on the line when arrayInt is declared (3rd set of while loop from validateUserInput method)
public static void main(String[] args) {
// Ask for user input
Scanner input = new Scanner(System.in);
//declare an array with index of 5
int array[] = new int[5];
//loop to prompt user to input 5 test scores, each of which are stored in array
for (int i = 0; i < array.length; i++){
System.out.println("Enter score " + (i+1) + ": ");
//array[i] = Integer.parseInt(input.nextLine());
String arrayInput = input.nextLine();
arrayInput = validateUserInput (arrayInput);
array[i] = Integer.parseInt(arrayInput);
}
//call method to display test scores
displayTestScores(array, array);
//exit out
System.out.println("Press any key to exit...");
input.nextLine();
System.exit(0);
}
//validate user input
public static String validateUserInput ( String arrayInput){
//variable to itirate through the string
int counter = 0;
//variable to index
int arrayInputLength = arrayInput.length();
//assign scanner for user input
Scanner input = new Scanner(System.in);
//loop to check if blank
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
//loop to check if user inputs numbers mixed with letters, iterate using counter
while (arrayInputLength > counter){
if (!Character.isDigit(arrayInput.charAt(counter))){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
counter = 0;
}
else{
counter ++;
}
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
//loop to check while there is something inputted, make sure only between 0 and 100
while (arrayInputLength > 0 ){
int arrayInt = Integer.parseInt (arrayInput);
if (arrayInt > 0 && arrayInt <= 100){
return arrayInput;
}
else {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
while (arrayInputLength == 0 ){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
return arrayInput;
}
validateUserInput has too much responsibility (and duplicate code). It's trying to validate the user input and also get new input. But that new input might not be valid either (which is causing the error in your question).
Separate getting user input from validating the input. Consider changing
public static String validateUserInput ( String arrayInput)
to
public static boolean isValidInput(String arrayInput)
It only checks to see if the input is valid. It does not prompt the user for new input.
Then within the main for loop, keep prompting the user for input until it is valid.
for(...) {
....
while (!isValidInput(arrayInput)) {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
}
....
}
I want the while loop to execute when the user's input is a non-integer value, an integer value less than 1, or an integer value greater than 3. Once the input is valid, I will use it. However, the loop only works when the user inputs a non-integer value. I have gone through the logic and I am still not sure what's wrong.
Code:
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
row = scnr.nextInt() - 1;
"while" works fine by itself. No "do" is required in this case. Here is your code:
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
int row = scnr.nextInt() - 1;
You need "do" when you want to execute code at least once and then check "while" condition.
Also each call for nextInt actually requires next int in the input. So, better use it only once like this:
int i;
while((i=scnr.hasNextInt() && (i > 3)) || (scnr.hasNextInt() && (i < 1)) || (!scnr.hasNextInt()))
I am not completly sure about this, but an issue might be calling scnr.nextInt() several times (hence you might give the value to a field to avoid this).
An easy to read solution would be introducing a tester-variable as #Vikrant mentioned in his comment, as example:
System.out.println("Please enter an integer value 1-3 for the row.");
boolean invalid=true;
int input=-1;
while(invalid)
{
invalid=false;
if(scnr.hasNextInt())
input=scnr.nextInt();
else
invalid=true;
if(input>3||input<1)
invalid=true;
if(!invalid)
break;
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
In this Java program the user is supposed to guess a number from 1 to 100, and then if you press S it shows you a summary of the tries. The problem is that I am taking the input string and converting it to a number so I can compare it to the range, but then I also need to be able to use that string as a menu input.
UPDATE How can i make the program go back to the menu option after the user guesses correctly. So after the user wins, i would like for the problem to display the summary report which can be otherwise accessed by using S
Here is my code
public class GuessingGame {
public static void main(String[] args) {
// Display list of commands
System.out.println("*************************");
System.out.println("The Guessing Game-inator");
System.out.println("*************************");
System.out.println("Your opponent has guessed a number!");
System.out.println("Enter a NUMBER at the prompt to guess.");
System.out.println("Enter [S] at the prompt to display the summary report.");
System.out.println("Enter [Q] at the prompt to Quit.");
System.out.print("> ");
// Read and execute commands
while (true) {
// Prompt user to enter a command
SimpleIO.prompt("Enter command (NUMBER, S, or Q): ");
String command = SimpleIO.readLine().trim();
// Determine whether command is "E", "S", "Q", or
// illegal; execute command if legal.
int tries = 0;
int round = 0;
int randomInt = 0;
int number = Integer.parseInt(command);
if (number >= 0 && number <= 100) {
if(randomInt == number){
System.out.println("Congratulations! You have guessed correctly." +
" Summary below");
round++;
}
else if(randomInt < number)
{
System.out.println("your guess is TOO HIGH. Guess again or enter Q to Quit");
tries++;
}
else if(randomInt > number){
System.out.println("your guess is TOO LOW. Guess again or enter Q to Quit");
tries++;
}
} else if (command.equalsIgnoreCase("s")) {
// System.out.println("Round Guesses");
// System.out.println("-------------------------");
// System.out.println(round + "" + tries);
} else if (command.equalsIgnoreCase("q")) {
// Command is "q". Terminate program.
return;
} else {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only E, S, or q.");
}
System.out.println();
}
}
}
You should check for the S/Q value first, then parse the string to an integer. If you catch NumberFormatException (thrown by Integer.parseInt()), you can determine if the input is a valid value. I would do something like that:
if ("s".equalsIgnoreCase(command)) {
// Print summary
} else if ("q".equalsIgnoreCase(command)) {
// Command is "q". Terminate program.
return;
} else {
try {
Integer number = Integer.parseInt(command);
if(number < 0 || number > 100){
System.out.println("Please provide a value between 0 and 100");
} else if(randomInt == number){
System.out.println("Congratulations! You have guessed correctly." +
" Summary below");
round++;
} else if(randomInt < number) {
System.out.println("your guess is TOO HIGH. Guess again or enter Q to Quit");
tries++;
} else if(randomInt > number) {
System.out.println("your guess is TOO LOW. Guess again or enter Q to Quit");
tries++;
}
} catch (NumberFormatException nfe) {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only a number, S, or q.");
}
}
With this algorithm (I'm sure it can be optimized), you treat following cases:
User enters s/S
User enters q/Q
User enters a non valid value (not a number)
User enters a non valid number (less than 0 or greater than 100)
User enters a valid number
To check if a string is an integer, just attempt to parse it as an integer and if an exception is thrown, then it is not an Integer.
See:
http://bytes.com/topic/java/answers/541928-check-if-input-integer
String input = ....
try {
int x = Integer.parseInt(input);
System.out.println(x);
}
catch(NumberFormatException nFE) {
System.out.println("Not an Integer");
}
Integer.parseInt(command) will give you NumberFormatException if the String is not valid. It is possible in your code if the user enters 'S' or 'E' which cannot be parsed to int value.
I have modified your code. Check this code :
while (true) {
// Prompt user to enter a command
SimpleIO.prompt("Enter command (NUMBER, S, or Q): ");
String command = SimpleIO.readLine().trim();
// Determine whether command is "E", "S", "Q", or
// illegal; execute command if legal.
int tries = 0;
int round = 0;
int randomInt = 0;
if(!command.equals("S") && !command.equals("E")) {
// Only then parse the command to string
int number = Integer.parseInt(command);
if (number >= 0 && number <= 100) {
if(randomInt == number){
You're trying to convert the incoming String to an int before you check if its an escape sequence (S or Q).
Try rearranging your if statement to check for S and Q first then try converting the value to an int.
I'd also recommend you wrap the Integer.parseInt call (it's subsequent, reliant code) in a try-catch block, so you can provided an error statement to the user if they type in anything that isn't an int
I am trying to validate input from a user.The user puts in Y coordinate a letter between (A-J) and x coordinate a number between (1-9).I can validate the y coordinate but am having trouble validating the x coordinate. I want it so if the user puts in something other than a number between 1 and 9 it keeps asking the user for valid input.
do {
// inner loop checks and validates user input
do {
System.out.println("Enter X Co-Ord (A-J), or Q to QUIT");
letter = input.next().toUpperCase(); // upper case this for
// comparison
if (letter.equals("Q"))
break; // if user enters Q then quit
String temp = "ABCDEFGHIJ";
while (temp.indexOf(letter) == -1) {
validString = false;
System.out.println("Please enter a valid input");
letter = input.next().toUpperCase();
col = temp.indexOf(letter);
}
if (temp.indexOf(letter) != -1) {
validString = true;
col = temp.indexOf(letter);
}
try {
System.out.println("Enter Y Co-Ord (0-9)");
row = input.nextInt();
} catch (InputMismatchException exception) {
validInt = false;
System.out.println("Please enter a number between 1 -9");
}
catch (Exception exception) {
exception.printStackTrace();
}
valuesOK = false; // only set valuesOK when the two others are
// true
if (validString && validInt) {
valuesOK = true;
}
} while (!valuesOK); // end inner Do loop
The output is:
Enter X Co-Ord (A-J), or Q to QUIT
d
Enter Y Co-Ord (0-9)
h
Please enter a number between 1 -9
Enter X Co-Ord (A-J), or Q to QUIT
Enter Y Co-Ord (0-9)
You just need to put a while loop around your nextInt() the same as you do when reading the letter:
System.out.println("Enter Y Co-Ord (0-9)");
row = -1
while (row < 0) {
try {
row = input.nextInt();
validInt = true;
} catch (InputMismatchException exception) {
System.out.println("Please enter a number between 1 -9");
row = -1;
validInt = false;
}
}
Just want to make the validation make more sense with the requirement, since human 's eye can skip easily the line nextInt()
String value = "";
System.out.println("Enter Y Co-Ord (1-9)");
while (!(value = input.next()).matches("[1-9]+")) {
System.out.print("Wrong input. Insert again: ");
}
System.out.println(value);
Of course, when you get the right value, then you can parse it to integer again (safely !!!)