Could you help me identify what I am missing with the code below? I am using Eclipse.
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
{
if (input.equalsIgnoreCase(("front door") || ("front") || ("basement") || ("basement entrance")))
if (input.equalsIgnoreCase(("front door") || ("front"))
System.out.println("Maggie went to the side of the home and open the basement door. As the door opened, she could smell the dust from inside.");
else
if ((input.equalsIgnoreCase("basement") || ("basement entrance")))
System.out.println("Maggie walks up the steps and slowly opens the front door.");
else
System.out.println("That is not a correct answer");
I think there are a few errors:
1. If-else logic:
a) if (input.equalsIgnoreCase(("front door") || ("front") ||
("basement") || ("basement entrance")))
if (input.equalsIgnoreCase(("front door") || ("front"))
What do you mean here? Second if is redundant.
b)
else
if ((input.equalsIgnoreCase("basement") || ("basement entrance")))
this part is unreachable, because if covers it.
Syntax error in if(condition).
Suppose it should look llke
String input = scanner.nextLine();
{
input = input.toLowerCase();
if (input.equals("front door") || input.equals("front"))
System.out.println("Maggie went to the side of the home and open the basement door. As the door opened, she could smell the dust from inside.");
else if (input.equals("basement") || input.equals("basement entrance"))
System.out.println("Maggie walks up the steps and slowly opens the front door.");
else
System.out.println("That is not a correct answer");
That's not how you use logical or operator, you have to do something like
if (input.equalsIgnoreCase("front door") || input.equalsIgnoreCase("front") ||
input.equalsIgnoreCase("basement") || input.equalsIgnoreCase("basement entrance")) {
...
}
Related
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!
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.
Programming beginner here, I am having trouble with error/exception handling as I do not have a clue how to do it. For my menu system (code below), I want it to alert users when anything other than 1-6 is entered, is try catch the best method? Can someone show me how it should be implemented?
do
if (choice == 1) {
System.out.println("You have chosen to add a book\n");
addBook();
}
///load add options
else if (choice == 2) {
System.out.println("Books available are:\n");
DisplayAvailableBooks(); //call method
}
////load array of available books
else if (choice == 3) {
System.out.println("Books currently out on loan are:\n");
DisplayLoanedBooks(); //call method
}
//display array of borrowed books
else if (choice == 4) {
System.out.println("You have chosen to borrow a book\n");
borrowBook(); //call method
}
//enter details of book to borrow plus student details
else if (choice == 5) {
System.out.println("What book are you returning?\n");
returnBook(); //call method
}
//ask for title of book being returned
else if (choice == 6) {
System.out.println("You have chosen to write details to file\n");
saveToFile(); //call method
}
while (choice != 1 && choice != 2 && choice != 3 && choice != 4 && choice != 5 && choice != 6) ;
menu();
keyboard.nextLine();//catches the return character for the next time round the loop
}
Try a switch statement
switch() {
case 1:
addBook();
break;
// etc ...
default:
System.out.println("Not a valid choice");
break;
}
The switch will also work with strings so you can add a q to the menu to quit or a b to go back to make a multi level menu.
This may be whats needed as all user input from readline is considered a string so unless you are converting the input to int, which will need to be wrapped in a try catch, this is the better option as the default will take care of any unexpected user input.
case "1": & case "q":
A more "clean" and much more understandable way to write it would be something like this
if(choice < 1 || choice > 6) {
//invalid input handling
}
while (choice >= 1 && choice <=6) {
// choice handling and program execution
}
Another option you can try is use a switch statement which you can study here
http://www.tutorialspoint.com/javaexamples/method_enum.htm
And the other comments are correct, this is not exception handling and rather undesirable input handling. Exception handling would be for example inputing a null and a null exception error is thrown. There you could use a try catch to continue running your program even if an error is thrown.
this is my first post here, but I often use this site to help me with coding issues I run into. I'm an intermediate level Java programmer. I'm going to college next year and I'm considering a minor in Computer Science.
I'm making a pretty basic mock-credit card validator that reads in a credit card, checks if it's valid, and then emails information to the user. This is not to be used for anything other than educational purposes.
So I have a bit of code that checks multiple conditions for a credit card string that someone types in. For example, as you'll see, it checks the starting digit, the name of the card, and the number of digits. It checks the conditions, and if they are met the program continues, if not it gives an error and stops immediately. I'm like 99% sure that I'm entering my information in correctly, but it gives me the error no matter what and I'm at a loss here.
Sorry if I typed so much, again I'm new here. So I'm asking for help on my logic here, thanks!
if((cardType.equals("Visa") && card.substring(0).equals("4")) && (length == 13 || length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("Master Card")) && (card.substring(0,1).equals("51") || card.substring(0,1).equals("52") || card.substring(0,1).equals("53") || card.substring(0,1).equals("54") || card.substring(0,1).equals("55")) && (length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("American Express") && card.substring(0,1).equals("37") && length == 15)){
System.out.println("Thank you, next step");
cardValid = true;
}
if(cardValid != true){
System.out.println("ERROR");
System.exit(0);
}
}
You are not using the substring method correctly. To get the first character as a substring, you need to use the two-argument version of substring, to supply a beginning index (inclusive) and an ending index (exclusive).
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
(The one-argument version of substring takes a substring from the given index through the rest of the string.)
The substring begins with the character at the specified index and extends to the end of this string.
Replace
card.substring(0).equals("4")
with
card.substring(0, 1).equals("4")
or just compare the character there.
card.charAt(0) == '4'
Next, to get the first two characters, again take into account the fact that the ending index is exclusive. Replace
card.substring(0,1).equals("37")
with
card.substring(0,2).equals("37")
The following should work.
You had some syntactic errors with String.substring. You can refer to a full list of String functions in the java documentation below:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
if((cardType.equals("Visa") && card.substring(0,1).equals("4")) && (length == 13 || length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("Master Card")) && (card.substring(0,2).equals("51") || card.substring(0,2).equals("52") || card.substring(0,2).equals("53") || card.substring(0,2).equals("54") || card.substring(0,2).equals("55")) && (length == 16)){
System.out.println("Thank you, next step");
cardValid = true;
}
if((cardType.equals("American Express") && card.substring(0,2).equals("37") && length == 15)){
System.out.println("Thank you, next step");
cardValid = true;
}
if(!cardValid){
System.out.println("ERROR");
System.exit(0);
}
}
Here is my code:
public static void nameset(){
int no = 1;
name = JOptionPane.showInputDialog(frame, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name.equals("") || name.equals(JOptionPane.CANCEL_OPTION));{
JOptionPane.showMessageDialog(frame,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name.equals("") || name.equals(JOptionPane.CANCEL_OPTION)){
if (no == 2){
JOptionPane.showMessageDialog(frame, "Seriously? Again?! that's it..");
if (name.equals(JOptionPane.CANCEL_OPTION)){
System.exit(0);
}else{
System.exit(0);
}
}
}
}
I want it so if you press the cancel option it tell you to restart. But if you press cancel, it shows an error in the console. I think it's the name.equals(JOptionPane.CANCEL_OPTION), But I'm not sure. Is there any reason for it not to work? Thanks in advance for any help.
The cancel button will always result in null being returned. See official JavaDoc:
Returns: user's input, or null meaning the user canceled the input
So your condition should be changed to:
if(name == null || name.equals(""))
and you also need to remove the semicolon after your first if statement! Otherwise the following block will always be executed.
Once that's fixed, your "exit after 3 times no" will not work because you're not actually looping your input dialog.
Try this
int no = 1;
String name = JOptionPane.showInputDialog(null, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name == null || name.equals(""));{
JOptionPane.showMessageDialog(null,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name == null || name.equals("")){
if (no == 2){
JOptionPane.showMessageDialog(null, "Seriously? Again?! that's it.."+name);
if (name == null || name.equals("")){
System.exit(0);
}else{
System.exit(0);
}
}
}