What alternatives are there for if else statements? - java

This is a method within my program and I cannot use a bunch of if-else statements for my code. I need alternatives.
public String bedRoom1(){
int newChoice10 = JOptionPane.showConfirmDialog(null,"Would "
+ "you like to explore this room?",
"question",JOptionPane.YES_NO_OPTION);
if (newChoice10 == JOptionPane.YES_OPTION){ //if the user would lieke to
// explore then they are given the option for which objects they woul like to explore
int newChoice4 = JOptionPane.showConfirmDialog(null,"Explore"
+ " the Rocking chair(type YES) or Window(type NO)?"
, "question",JOptionPane.YES_NO_OPTION);
//The following if else statments are still within
//the first statement of the first if statement
if (newChoice4 == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null,"Chair starts "
+ "rocking with no one in it");
}else{
JOptionPane.showMessageDialog(null, "You see a child outs"
+ "ide on a swing and he suddenly vanishes.");
}
}else if (newChoice10 == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null,"You have chosen not "
+ "to explore Bedroom 1 and therefore continue "
+ "into the following room");
}
return null;
}
Can you please provide examples. Thank you in advance.

you can use showOptionDialog with all your choices instead of showConfirmDialog
and use switch - case instead of if then else

Related

How to exit from foreach loop? Which using enum data [duplicate]

This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
Closed 4 years ago.
I wanted to implement a game with levels and after winning the current level, the user can solve another one. I did it by for each loop using enum data. If you have a another way of solving this problem, please share with me. Program already changes levels after right decision from user, but I want to implement that if user provides a wrong answer, it exits from main loop. I tried to solve it with the break operator, but it doesn't work. If you have another solution to this problem, please share with me.
static void levelchanger() {
Levelinfo[] types = Levelinfo.values();
for (Levelinfo arr : types) {
while (arr.moves != 0 && arr.display != arr.goal) {
System.out.println("It is " + arr + " level. You have: " + arr.moves + " moves. Goal: " + arr.goal);
System.out.println("Step: 1) " + arr.gnumbers[0] + " 2) " + arr.gnumbers[1]);
Scanner in = new Scanner(System.in);
int action = in.nextInt();
switch (action) {
case 1:
arr.display += arr.gnumbers[0];
System.out.println("Result: " + arr.display);
break;
case 2:
arr.display += arr.gnumbers[1];
System.out.println("Result: " + arr.display);
break;
}
arr.moves--;
if (arr.moves == 0 && arr.display != arr.goal) {
System.out.println("You don't have more moves!");
break;
} else if (arr.display == arr.goal) {
System.out.println("Alright! Next level");
}
}
}
}
add tag to the loop
a: for (;;)
{
while()
{
if(condition)
break a;// at your condition write like this
}
}
The break statement will only break out of the current loop.
You can either change your break to a return if there is nothing else you want to do after the for, or restructure your code to make use of smaller methods, so that you avoid so much nesting within one method.
You can also add a boolean variable which is set to false, and checked in the for loop but will probably make the code dirtier.

How do I show a message before system.exit in Java

I am trying to cover possible options when using the JOptionPane.showInputDialog box.The user must enter a "Y" to continue running the code, "N" will cancel the procedure and clicking the cancel button should do the same as typing "N". But, when the user clicks cancel, I want to show the a message like "You have chosen to cancel the order" before the System.exit(0) runs. I have not been able to get that message to display. Below is the code I have so far:
inputStr = JOptionPane.showInputDialog("Enter an order (Y/N)");
if(inputStr.equalsIgnoreCase("N")){
JOptionPane.showMessageDialog(null, "Since you are not entering an order....\n" +
"The program will close.");
System.exit(0);
}
else if(inputStr.equals(null)){
JOptionPane.showMessageDialog(null, "You have chosen to cancel this order");
System.exit(0);
}
else if(!inputStr.equalsIgnoreCase("Y")){
JOptionPane.showMessageDialog(null, "You have entered an invalid character.\n" +
"Enter a 'Y' or 'N' only.");
continue;
}
I would use the YES_NO_CANCEL_OPTION:
Object[] options = {"Yes","No","Cancel"};
int n = JOptionPane.showOptionDialog(frame,
"Continue?",
"Would you like to continue?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if (n == JOptionPane.YES_OPTION) {
System.out.println("Clicked Yes");
} else if (n == JOptionPane.NO_OPTION) {
System.out.println("Clicked No");
} else if (n == JOptionPane.CANCEL_OPTION) {
System.out.println("Clicked Cancel");
} else {
System.out.println("something else (like clicked the 'x' button)");
}
Try changing inputStr.equals(null) to inputStr == null
Works fine as long as you change the if statments around to what they are below.
String inputStr;
inputStr = JOptionPane.showInputDialog("Enter an order (Y/N)");
if(inputStr == null){
JOptionPane.showMessageDialog(null, "You have chosen to cancel this order");
System.out.println("hello");
System.exit(0);
}
else if(inputStr.equalsIgnoreCase("N")){
JOptionPane.showMessageDialog(null, "Since you are not entering an order....\n" +
"The program will close.");
System.exit(0);
}
else if(!inputStr.equalsIgnoreCase("Y")){
JOptionPane.showMessageDialog(null, "You have entered an invalid character.\n" +
"Enter a 'Y' or 'N' only.");
}
Think about
if(inputStr.equals(null)){
Does it make sense to call the 'equals()' method on a 'null' object? Because if inputStr is null, then you would not be able to call a method on it.
The correct syntax would be:
if(inputStr == null){
and do this as the first 'if', to protect you from a NPE.
This what i will do
String inputStr = JOptionPane.showInputDialog("Enter an order (Y/N)");
if (inputStr == null || inputStr.isEmpty()) {
JOptionPane.showMessageDialog(null, "You Cancelled");
} else {
if (inputStr.equalsIgnoreCase("N")) {
JOptionPane.showMessageDialog(null,
"Since you are not entering an order....\n"
+ "The program will close.");
System.exit(0);
} else if (!inputStr.equalsIgnoreCase("Y")) {
JOptionPane.showMessageDialog(null,
"You have entered an invalid character.\n"
+ "Enter a 'Y' or 'N' only.");
}
}
Goodluck
Make a delay in between exit(0) and message with javax.swing.Timer
And Change
if(inputStr.equals(null)){
with
if(inputStr == null){
== will always compare for identity - i.e. whether the two values are references to the same object. This is also called reference equality. Java doesn't have any user-defined operator overloading.
.equals() will call the virtual equals method declared by Object, unless a more specific overload has been introduced by the compile-time type of inputStr.
Of course, if inputStr is null then you'll get a NullPointerException when you try to call inputStr.equals(null).

User input if statements skipping

So what I am trying to accomplish is having the user be able to order a item, so far just potatoes, and then to confirm the order using a "yes" or "no" input. What is happening however is the secondary input if statements are bing skipped over and the rest of the code runs. Can anyone tell why these if statements are not being implemented properly?
if(next.contains("potatoes")); {
// Add in the quantity function later;
System.out.println("\nAre you sure you want to add potatoes?");
}
if(next.contains("yes")); {
System.out.println("\nYour basket:" + itemOne +" " + potatoCost);
}
if(next.contains("no")); {
System.out.println("You have not added " +itemOne + " to your cart.");
}
}
while ( next.equalsIgnoreCase("exit") == false );
System.out.println("You have decided to stop shopping!");
System.exit(0);
}
}

Do while loop error

Hey guys I have here a program wherein a user needs to guess the word which is being asked by the program itself. The codes doesn't have syntax errors, but my problem here is that every time you input the correct word that is being asked for, the JOptionPane (ErrorMessage) still appears.
What I want to happen is that, the user can only have 5 trials, once the user entered a wrong word at the last trial given, it should display the correct word that is asked for. And once the user entered the correct word, it should go to the next word. Please help me fix this I'm stuck in here for like 3 hours already. Thank you very much.
private void guessedWordActionPerformed(java.awt.event.ActionEvent evt) {
int trials = 5;
boolean tryAgain = true;
do{
if (wordLibrary.isCorrect(wordIdx, guessedWord.getText())){
JOptionPane.showMessageDialog(null, "Your answer is correct! Guess another word.","", JOptionPane.INFORMATION_MESSAGE);
getRootPane().setDefaultButton(nextTrial);
guessedWord.setText("");
wordIdx = (wordIdx + 1) % wordLibrary.getSize();
scrambledWord.setText(wordLibrary.getScrambledWord(wordIdx));
guessedWord.setText("");
getRootPane().setDefaultButton(guessButton);
guessedWord.requestFocusInWindow();
tryAgain = false;
}
else if (!wordLibrary.isCorrect(wordIdx, guessedWord.getText())) {
JOptionPane.showMessageDialog(null, "Your answer " + guessedWord.getText() + " is wrong.\n Number of trials remaining: " + trials ,
"Incorrect Answer", JOptionPane.ERROR_MESSAGE);
trials--;
guessedWord.setText("");
tryAgain = true;
}
}while(tryAgain && trials > 0);
guessedWord.requestFocusInWindow();
}
//This is the isCorrect method
public boolean isCorrect(int idx, String userGuess) {
return userGuess.equalsIgnoreCase(getWord(idx));
}
This is happening in your action performed. When you loop, you're not giving the user any time to enter new information.
Why do you want to loop here? You don't need it. Just check once. If they're wrong change the components and wait for ActionPerformed to be called again.
If you want to give a maximum number of trials, then you should use some form non-local variable to store it.
When you first give a wrong answer, guessedWord's text becomes the empty String "", so at the next iteration, it will never be equal to the given word, because the String that you get with guessedWord.getText() will now be "".
You need to ask the user for a new word and then get the NEW word!
For example, you could set a private variable int trials in your class, initialized with 5 (in your main method) and another one, boolean tryAgain initialized with true. Then the above method could be written as:
private void guessedWordActionPerformed(java.awt.event.ActionEvent evt){
if (tryAgain && trials > 0) {
if (wordLibrary.isCorrect(wordIdx, guessedWord.getText())){
JOptionPane.showMessageDialog(null, "Your answer is correct! Guess another word.","", JOptionPane.INFORMATION_MESSAGE);
getRootPane().setDefaultButton(nextTrial);
guessedWord.setText("");
wordIdx = (wordIdx + 1) % wordLibrary.getSize();
scrambledWord.setText(wordLibrary.getScrambledWord(wordIdx));
guessedWord.setText("");
getRootPane().setDefaultButton(guessButton);
guessedWord.requestFocusInWindow();
tryAgain = false;
} else {
trials--;
JOptionPane.showMessageDialog(null, "Your answer " + guessedWord.getText() + " is wrong.\n Number of trials remaining: " + trials ,
"Incorrect Answer", JOptionPane.ERROR_MESSAGE);
guessedWord.setText("");
tryAgain = true;
}
} else {
//show "the correct word was..."
}
guessedWord.requestFocusInWindow();
}

Java: Code ain't working the right way

First you have to know that I'm a noob to Java, i just started to code and it's my first programming language. So please don't be angry if I'm begin a bit stupid, I just wanna learn to code - Thanks
I'm trying to make a simple " guessing game ", but my code aren't waiting for the user-input.
please help me, I don't know what to do.
My code:
public static void main(String[] args)
{
//Creating the scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Creating the two random numbers.
Random rand = new Random();
int userNumber = rand.nextInt(10) + 1;
int comNumber = rand.nextInt(10) + 1;
//Asks the user what to do.
System.out.println("Your number is: " + userNumber +" of 10");
System.out.println("Do you think that your number is Heigher(H), Lower(L) or Equal To(E) the computers number");
//Checking if the user is right.
//If the user types in LOWER
if(userNumber < comNumber && input.equals("L"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber < comNumber && !input.equals("L"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in EQUAL TO.
if(userNumber == comNumber && input.equals("E"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber == comNumber && !input.equals("E"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in HEIGHER.
if(userNumber > comNumber && input.equals("H"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber > comNumber && !input.equals("H"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
else
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
}
I would be happy if you could help me out whit my problem, and tell me how I can remove the #SuppressWarnings("resource") / explain why it have to be there.
You're using Scanner wrong. You need to call scanner.nextLine() to get input (a String) from the user, and you need to convert the String to an integer (with Integer.parseInt) to compare it with other ints.
You're going to have to import java.util.Scanner into your project. Take a look at this link that will give you plenty of information about it.
Edit: Just noticed you had it at the top. The next thing you should do is create a variable, say "guess" of type string, and you want to assign input.next() to that variable. Then you can replace the input.equals() functions with the guess.equals() function.
http://www.homeandlearn.co.uk/java/user_input.html
You should import java.util.*;
And You aren't taking any input from user, try
int inp=input.nextInt();
To answer your original question, you are getting an error because you aren't importing java.util.Scanner
import java.util.Scanner;
To address some of the other issues:
You are not reading in anything from the user. You use the Scanner methods to do this.
String guess = input.nextLine() is what I would use.
Secondly, your if statements would not work the way you are using them. This may not be the most compact but it is good for readability.
if(guess.equals("L")){
if(userNumber < comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else if(guess.equals("E")){
if(userNumber == comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else if(guess.equals("H")){
if(userNumber > comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else {
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
I also suggest closing the Scanner as good practice at the end. input.close()
You might want to read the documentation of the Scanner class. It has some examples on how to use it properly.
The main problem is in your if statements: With input.equals("L") you are asking if the scanner object is equal to the string "L", which is impossible, since they aren't the same type.
To get a string from the input stream you could use input.next() and compare that to "L". Remember though to only call it once before all the ifs, otherwise the programm waits for a new input at every condition check.
Regarding the warning:
As you can read in the documentation, Scanner needs to be closed with input.close() after use.
And just as a hint, never use the #SuppressWarnings annotation if you don't know what your are suppressing. It is meant as a tool for you to use when you know that something the compiler warns you about cannot happen.
In this case it tried to warn you about a resource leak, which is absolutely correct.
EDIT:
Just as an idea how you could improve your design. You could do something similar to:
String expectedInput;
if (userNumber < comNumber) {
expectedInput = "L";
} else if (userNumber == comNumber) {
expectedInput = "E";
} else {
expectedInput = "H";
}
String userInput = input.next();
if (userInput.equals(expectedInput)) {
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
You would still have to check for wrong input though.
This has a more natural flow to the logic and is easier to read.
Another advantage would be that you are separating two different concepts: finding out who had the higher number and finding out if the user guessed right. This might seem like a little thing now, but things like the seperation of concepts and levels of abstraction will become more important the more complex your software gets.
Just had another idea. You could even get rid of the code duplication in the last bit and add a check for wrong input like this:
String userInput = input.next();
boolean isInputValid = Arrays.asList("L", "E", "H").contains(userInput);
if (isInputValid) {
String rightWrong = userInput.equals(expectedInput) ? "right" : "wrong";
System.out.println("You are " + rightWrong + ". The computer's number is: " + comNumber);
} else {
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
Though it is debatable if using a ternary operator is good style...

Categories