Error checking in Java: S to Start and Q to Quit - java

I'm a student currently taking basic Java classes.
I'm working on a code that asks the user an input for a game to "start" and to "quit". Sooo I chose the string "S" and "Q" respectively. If the user enters S, the game proceeds. If the user enters Q, the program displays "Thanks for playing" or something. If the user enters something other than S and Q, the program asks again until it gets a valid input. I almost got everything correctly except for the error checking part. Any possible suggestions to fix my code?
Thank you in advance! :)
(partial code)
Scanner scan = new Scanner(System.in);
String userInput;
boolean game = false;
System.out.println("Welcome to the Game! ");
System.out.println("Press S to Start or Q to Quit");
userInput = scan.nextLine();
if (userInput.equals("S")){
game = true;
} else if (userInput.equals("Q")){
game = false;
} else {
do {
System.out.println("Invalid input! Enter a valid input: ");
userInput = scan.nextLine();
} while (!"S".equals(userInput)) || (!"Q".equals(userInput)); // I'm not sure if this is valid???
}
if (userInput.equals("S")){
///// Insert main code for the game here////
} else if (userInput.equals("Q")){
System.out.println("Thank you for playing!");
}

You're creating an infinite loop:
while (!"S".equals(userInput)) || (!"Q".equals(userInput)); // always true
For this condition to not hold you'll need an input that is equal to "S" and to "Q" together. It's easy to see applying De-Morgan's law:
while (!("S".equals(userInput)) && "Q".equals(userInput))); // always true
Obviously, it won't happen.
You probably want:
while (!"S".equals(userInput)) && (!"Q".equals(userInput));

I can't vote on answers yet, but the prior one is correct.
Breaking out the logic:
input = "Z"
while( !(S==Z) || !(Q==Z) ) -> while( !(F) || !(F) ) -> while( T || T ) -> repeat
input = "Q"
while( !(S==Q) || !(Q==Q) ) -> while( !(F) || !(T) ) -> while( T || F ) -> repeat
Switching to "and" makes case #2 work.
Do you do anything with your "game" boolean? If the user enters the while loop then the boolean will always be false.

Related

Java loop confusion requiring assistance

So i need help, i am trying to input a Y/N program but it is not accepting a big 'Y' or 'N'. Also another thing that i am trying to do is after pressing 'Y'/'y' i am trying to get the program to loop back to the code written above. Example a program that displays '123' and do i need to continue? Y/N, if entered yes it goes back up to restart the program from scratch. Please help me.
System.out.println("continue? Yes or no ");
char check = s.next().charAt(0);
while (check != 'y' && response != 'n')// corrected this part, however need help with restarting the loop back to the first line of code in a loop {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
} if ((check == 'n') || (check == 'N')) {
// I tried (check == 'n' || check == 'N')
System.out.println("Program terminated goodbye.");
System.exit(0);
} else if (check == 'y') {
//need help with restarting the loop back to the first line of code in a loop
}
I think this is what you are looking for.
char check;
Scanner scanner = new Scanner(System.in);
do
{
//your piece of code in here e.g.
System.out.println("Printed 123");
System.out.println("Do you wish to continue?[Y/y] or [N/n]");
choice = scanner.next().charAt(0);
}while (check =='Y' || check == 'y');
System.out.println("Program terminated goodbye.");
A do-while loop runs at least once before the condition is checked and so when a user enters either Y or y, then the condition will be true, meaning that they wish for the loop to run again. If the user enters any other value, then the condition will become false since choice is neither Y nor y and the loop will terminate.
Use String.equals() to compare the value of strings, == compares the strings in memory.
If you want to check without case-sensitive, you should convert the char to a String, then do s1.equalsIgnoreCase(s2);
So
while(true) {
System.out.println("Continue? [Y/N]");
char check_char = s.next().charAt(0);
String check = Character.toString(check_char);
while(check.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
}
if (check.equalsIgnoreCase("n")) {
System.out.println("Program terminated goodbye.");
System.exit(0);
}
}
For returning to the first line, I used a while loop that loops forever.
To the end if it is n then exits, otherwise it returns back to the first line of the loop.

How Can I get input from user until user enter the right input in java?

i try to make a menu in java and get user input Until user enter the right input, so i used while() in my code. but when i run my code , the only things is run is while loop for whole time that i enter input , even the right input.
//Show Menu Of Languages
System.out.print("Welcome To iHome Application \n \n Pleas Choose You're Wanted Language" +
"(Enter Number Of Language Or Type You're Wanted Language) : \n 1)English \n or \n 2)Persian " + "\n \n");
//Get Input From User
Scanner input = new Scanner(System.in);
String MenuLanguage = input.next();
//Get User Language Until User Enter The Right Format
while (!MenuLanguage.equalsIgnoreCase("1") || (!MenuLanguage.equalsIgnoreCase("English")) ||
(!MenuLanguage.equalsIgnoreCase("2")) || (!MenuLanguage.equalsIgnoreCase("Persian")) ) {
System.out.print("\n Pleas Enter An Option From Above Menu. Try Again. \n");
MenuLanguage = input.next();
}
if ((MenuLanguage.equalsIgnoreCase("1")) || (MenuLanguage.equalsIgnoreCase("English"))) {
} else if ((MenuLanguage.equalsIgnoreCase("2")) || (MenuLanguage.equalsIgnoreCase("Persian"))) {
System.out.print("Sorry. Persian Language Will Be Available Soon.");
}
but always my output is :
"Pleas Enter An Option From Above Menu. Try Again."
whats is my problem?
In your while loop, you check for OR (||). Replace it by AND (&&)
while (!MenuLanguage.equalsIgnoreCase("1") && (!MenuLanguage.equalsIgnoreCase("English")) &&
(!MenuLanguage.equalsIgnoreCase("2")) && (!MenuLanguage.equalsIgnoreCase("Persian")) )
A condition cannot meet OR with different input. If it's one thing, it will not be the 3 other things. With and, you can check it's neither of the 4 conditions.

Trying to validate whether or not the user typed in Yes or No

So I am trying to validate whether the user typed in a Yes or No and to continue asking until they type in one or the other. This is my code so far.
System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");
String input2 = scan.nextLine();
boolean d = input2.equals("Yes");
System.out.println(d);
while ((d != false) || (d != true)) {
System.out.println("Invalid Input. Please try again");
input2 = scan.nextLine();
d = input2.equals("Yes");
System.out.println(d);
}
Where am I going wrong? I am new to java. Any help would be greatly appreciated.
Edit: I am awful at writing. What I am going for is this type of logic.
Ask the user if they would like a diamond instead of a pyramid.
a. The user must type “Yes” or “No”.
b. If the user types neither of these, ask again until they provide appropriate input.
You are ending up having an infinite loop at
while ((d != false) || (d != true))
since d being a boolean even when updated would either be true or false and in both the cases would satisfy the above condition. Instead you can change it to
System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");
String input2 = scan.nextLine();
boolean d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No"); // confirms if the user input is Yes/No or invalid other than that
....
while (!d) { // d==false ' invalid user input
System.out.println("Invalid Input. Please try again");
input2 = scan.nextLine();
d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No");
System.out.println(d);
// also printing a boolean would print either true or false base on your input; you migt want to perform some other action
} // this would exit on user input "Yes"
Booleans can ONLY equate to true or false so your while loop is going to execute no matter what because d will be true or it will be false. I think you want to just do
while (d != true)
You are using or(||) operator in your conditions whenever user typed one of your condition is false and other is true so that's why its not working fine.
if you want to stop asking at true value write below condition.
while(d != true)

Handling exceptions in Java: How to reject int?

I'm having a problem handling exceptions. Honestly, I really don't understand how it works since I self study.
I'm working with a program where there would be a main menu with the following choices.
Odd/Even - asks an integer input from user and identify if it is an odd or even. Program would continuously ask for an integer input if the user keeps on giving character inputs. (I was able to do this but I keep on getting errors when I use br.readLine() in getting input. Pls see codes below. So I used the normal parsing. Since I didn't use Buffered Reader, I try to delete it but the Odd/Even program wouldn't handle the exception without it.)
Vowel/Consonant - asks the user for a character input and identify if it is a vowel or a consonant. Program should reject integer inputs. The program I made with the codes below doesn't reject integer inputs. I tried searching for answers but I can't find one.
Please ignore for now.
My problem/s involve/s the following questions.
1. Why doesn't the program Odd/Even handle the NumberFormat exception whenever I try to delete the BufferedReader line even though it wasn't used in the whole program?
How can I reject integer inputs for the Vowel/Consonant program?
Here is a video when I tried to run the program.
http://tinypic.com/r/24ou9kz/9
When I exit the program, the console shows this.
Exception in thread "main" java.lang.NumberFormatException: null at
java.lang.Integer.parseInt(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source)
import javax.swing.JOptionPane;
import java.io.*;
import java.util.InputMismatchException;
public class DoWhileIf {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
int choice, num = 0;
char again = 0;
boolean err = true;
do {
input = JOptionPane.showInputDialog("Menu\n[1] Odd/Even\n[2] Vowel/Consonant\n[3] CQM\n[4] Fuel Efficiency\n[5] Scholarship\n[6] Exit program.\n\nEnter Choice.");
choice = Integer.parseInt(input);
if (choice == 1) {
do {
do {
try {
input = JOptionPane.showInputDialog("Input an integer : ");
num = Integer.parseInt(input);
err = false;
} catch (NumberFormatException o) {
JOptionPane.showMessageDialog(null,"Error!");
err = true;
}
} while (err);
if (num % 2 == 0) {
JOptionPane.showMessageDialog(null,"Even.");
}
else {
JOptionPane.showMessageDialog(null,"Odd.");
}
do {
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
again = input.charAt(0);
} while (again != 'Y' && again != 'y' && again !='N' && again !='n');
} while (again == 'Y' || again == 'y');
}
if (choice == 2) {
char letter = 0;
do {
do {
try {
input = JOptionPane.showInputDialog("Character : ");
letter = input.charAt(0);
err = false;
} catch (InputMismatchException a) {
JOptionPane.showMessageDialog(null,"Error!");
err = true;
}
} while (err);
if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U') {
JOptionPane.showMessageDialog(null,"Vowel");
}
else {
JOptionPane.showMessageDialog(null,"Consonant");
}
do {
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
again = input.charAt(0);
} while (again != 'Y' && again != 'y' && again !='N' && again !='n');
} while (again == 'Y' || again == 'y');
}
} while (choice <= 0 || choice > 6 || again == 'N' || again == 'n');
}
Why doesn't the program Odd/Even handle the NumberFormat exception whenever I try to delete the BufferedReader line even though it wasn't
used in the whole program?
I am not able to duplicate this problem. I removed the BufferedReader and option #1 works the same as it did before. I entered integer values, special characters, letters, spaces and it works fine.
How can I reject integer inputs for the Vowel/Consonant program?
You could modify your else condition from this:
else {
JOptionPane.showMessageDialog(null,"Consonant");
}
to this:
else if(Character.isLetter(letter)){
JOptionPane.showMessageDialog(null,"Consonant");
}
else{
JOptionPane.showMessageDialog(null,"Error! You must enter a valid letter.");
}
When I exit the program, the console shows this.
Exception in thread "main" java.lang.NumberFormatException: null at ...
Regarding the NumberFormatException you're seeing, I'm guessing you're pressing the Cancel button on the dialog. When you press cancel the variable input receives the value null. When you try to parse null as an integer it fails and throws the exception:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at exception.DoWhileIf.main(DoWhileIf.java:18)
Line 18 is this line: choice = Integer.parseInt(input);
Notice how the exception told us - java.lang.NumberFormatException: null which tells us that the parameter being passed to the parseInt method is null.
Lastly some additional thoughts for you to consider:
Whenever you get input from the user you must account for all the possibilities somehow. For example when you have code like this:
letter = input.charAt(0);
you're not accounting for the possibility that the input could be null or empty in which case this logic will throw an exception.
A concrete example is when the user clicks Cancel on the dialog that asks whether they want to try again:
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
When the user clicks Cancel on this dialog the same thing happens that I described above regarding the NumberFormatException - input becomes null. If you try to use input like this:
again = input.charAt(0);
it will fail with the exception:
Exception in thread "main" java.lang.NullPointerException
because you can't invoke a method on a null.
Another example is when the user enters nothing at the main menu but simply presses OK. The result is this exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
This happens because input was set to an empty string and parseInt does not know how to convert empty string into an integer value.
Another item I want to bring up is that you're using this same piece of code over and over again. Whenever you have code you want to reuse you should not copy and paste it but instead create a method, object, or other construct so that you can refer to it.
do {
input = JOptionPane.showInputDialog("Try again? Press Y for yes or N to go back to main menu.");
again = input.charAt(0);
} while (again != 'Y' && again != 'y' && again !='N' && again !='n');
Breaking up your logic into smaller more manageable pieces will help you to debug, test, and maintain your code more easily.
Another point I want to touch on regarding this same block of logic is that you're using the same kind of dialog to ask for many different kinds of input. Since you're using a GUI dialog, you could use a dialog that is better suited to your task such as one that asks the user to press either a Yes button or No button.
You can learn more about different kinds of dialogs by reading the How to Make Dialogs Tutorial
Here is an example of how you could create a more friendly dialog:
/**
* Asks the user if they want to try something again and
* returns a boolean representing the user's response.
* #return true if the user answers Yes, false otherwise.
*/
private static boolean promptToRepeatSelectedOption(){
int n = JOptionPane.showOptionDialog(null,
"Try again?",
"Repeat Selection",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
null,
null);
return n == JOptionPane.YES_OPTION;
}
The above method, when invoked, will create and display a dialog with two buttons - Yes and No - and the user will have to select one of them or close the dialog. The logic simply looks for if the user said Yes (by clicking the Yes button) and returns true when that is the case. If the user closes the dialog or chooses the No option the method returns false simply because either of those two scenarios will cause the n == JOptionPane.YES_OPTION comparison to result in a value of false.
You can replace your entire loop with a call to this method like this:
First, define a variable to hold the user's response.
boolean repeat = false;
Then invoke the method and set the variable to its result:
repeat = promptToRepeatSelectedOption();
Now replace the outer loop condition
while (again == 'Y' || again == 'y');
with this: while (repeat);
and finally replace part of the outermost loop condition
again == 'N' || again == 'n'
with this: !repeat
One final thought is that you're using very general error messages when the user enters something incorrect or invalid:
JOptionPane.showMessageDialog(null, "Error!");
It's always better to explain to the user a little bit about what they did wrong so that they know how to avoid the error next time. You should probably consider adding more detail to your error messages.
Hope this helps!

exit program do-while loop in java

I am working on a java program. Right now everything is totally working, and all my functionality is there. However, the part I am stuck on is how to exit out of the program in a do-while loop. I must be getting the syntax wrong.
Basically, I set a switch done which reacts to a user's input. Right now, it's working and loops through the program, but it does not exit if I say "no" to continuing.
Here is the part of the code this is happening:
public void main() {
String userInput;
boolean done = true;
Scanner keyboard = new Scanner(System.in);
do {
System.out.println("Welcome to Hangman!");
System.out.println("Do you want to play?");
userInput = keyboard.next();
if (userInput.equals("Yes") || userInput.equals("yes") || userInput.equals("y") || userInput.equals("Y")) {
done = false;
} else if (userInput.equals("n") || userInput.equals("no") || userInput.equals("NO") || userInput.equals("No")) {
done = true;
}
while (!done) {
System.out.println(getDisguisedWord());
System.out.println("Guess a letter: ");
String guess = keyboard.next();
makeGuess(guess);
if (gameOver()) {
String ui;
System.out.println("Do you want to play again?");
ui = keyboard.next();
if (ui.equals("Yes") || ui.equals("yes") || ui.equals("y") || ui.equals("Y")) {
done = false;
} else {
done = true;
}
}
}
} while(done);
}
any tips on how I could handle this better?
Your problem isn't what you think it is. To compare Strings, you need to use their built-in equals() method: ui.equals("Y"). Using == to compare them will always return false. For more information, see How do I compare strings in Java?.
Also, you need to flip your done = true and done = false statements (if the user says yes to playing again, they aren't done yet).
Finally, I would recommend changing your keyboard.next() calls to keyboard.nextLine() calls, or else you may run into weird issues, especially if the user enters input that includes whitespace.
EDIT: I noticed some more issues. You're while loop should be while(!done) instead of while(done). Also, I would get rid of your do-while loop, because the while loop is already allowing the user to play as many times as they want, so it is unnecessary.
boolean flag = true;
Scanner sc = new Scanner(System.in);
do{
System.out.println("***********************************************************");
System.out.println("Welcome to the School Admissions App !!! Press X for exit");
System.out.println("***********************************************************");
System.out.println("Enter the Student Name: ");
String student_name=sc.next();
System.out.println("press y to use this application again. press x to exit from this application ");
String input_user=sc.next();
if(input_user.equalsIgnoreCase("y")){
flag=true;
}else{
flag=false;
System.out.println("Thanks for using it.");
}
}while(flag);
U should use equals method for comparing string value in if statment. ui.equals("yes").

Categories

Resources