How do I show a message before system.exit in Java - 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).

Related

What alternatives are there for if else statements?

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

How to use if else to set var value in TextField

can I ask how I can instantly equal my TextField named txtUserName into 'Aime' and also my txtPassword equal to 'Joy' so that it will show the message "User Name and Password Match!" ? Anyone? Please help me :(
public void actionPerformed(ActionEvent e){
if (e.getSource()== btnClear){
txtUserName.setText("");
}
if(e.getSource() == btnLogin){
if (txtUserName.setText="Aime" && txtPassword.setText="JOy")){
JOptionPane.showMessageDialog(null, "User Name and Password Match!");
}
else {
JOptionPane.showMessageDialog(null, "User Name and Password Invalid!");
}
These are the Small modifications needed.
if (txtUserName.getText().equals("Aime") && txtPassword.getText().equals("Joy")){
JOptionPane.showMessageDialog(null, "User Name and Password Match!");
}else{
JOptionPane.showMessageDialog(null, "User Name and Password Invalid!");
}
For your reference : What is the difference between == vs equals() in Java?
you have two problems here:
txtUserName.setText="Aime" && txtPassword.setText="JOy"
am guessing you are trying to check the user input so you need to use the gettext method...
on the other hand you can not compare strings using ==, but furthermore you mistyped the == and are instead of comparing assigning, assignment that is invalid since you can not set the text of that view in that way...
try instead
txtUserName.getText().toString().equals("Aime") && ...

Why does my program give the wrong output once you have clicked a button?

In my program I use a JOptionPane.showConfirmDialog to prompt the user if they are sure they want to exit the simulation; if you click "NO" the prgoram should print out "Continuing siumlation..." and continue on with the program however I have found that when you click no it prints out "Continuting simulation" and then straight after "Maintenance will not be carried out, exiting Simulation..."
Can anyway help me find out as to why this happens?
if(main.equalsIgnoreCase("N") | main.equalsIgnoreCase("NO")){
result = JOptionPane.showConfirmDialog(null, "WARNING! Are you sure you don't want to carry out maintenance? The simulation will stop if you click YES. ", "TERMINATE THE SIMULATION? ", JOptionPane.YES_NO_OPTION);
if(JOptionPane.NO_OPTION == result){
System.out.println("Continuing Simulation...");
}
if (JOptionPane.YES_OPTION == result) {
Result2 = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the simulation?", "Are You Sure?", JOptionPane.YES_NO_OPTION);
}
if(JOptionPane.YES_OPTION == Result2){
System.out.println("Maintenance will not be carried out, exiting Simulation...");
try{
System.exit(0);
}
finally{
System.err.println("Exiting...");
System.exit(1);
}
}
if (JOptionPane.NO_OPTION == Result2) {
System.out.println("Continuing simulation...");
}
}
If you click "No" in the first dialog, then you do not assign any value to Result2 because you're not showing the second dialog. However you're still using the value of Result2 in this if-statement if(JOptionPane.YES_OPTION == Result2){.
The problem is, if Result2 is an instance variable, and you haven't assigned a value to it yet, then it has the default value for the type int, which is zero.
And the value of the constant JOptionPane.YES_OPTION is also zero. So that if-statement evaluates to true and it prints the maintenance message and exits.
You should nest the if-statements so that the check for the value of Result2 is only executed when you have assigned a meaningful value to it, like this:
if (JOptionPane.YES_OPTION == result) {
Result2 = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the simulation?", "Are You Sure?", JOptionPane.YES_NO_OPTION);
if(JOptionPane.YES_OPTION == Result2){
System.out.println("Maintenance will not be carried out, exiting Simulation...");
try{
System.exit(0);
}
finally{
System.err.println("Exiting...");
System.exit(1);
}
}
if (JOptionPane.NO_OPTION == Result2) {
System.out.println("Continuing simulation...");
}
}
Try this :
if(main.equalsIgnoreCase("N") | main.equalsIgnoreCase("NO")){
result = JOptionPane.showConfirmDialog(null, "WARNING! Are you sure you don't want to carry out maintenance? The simulation will stop if you click YES. ", "TERMINATE THE SIMULATION? ", JOptionPane.YES_NO_OPTION);
if(JOptionPane.NO_OPTION == result){
System.out.println("Continuing Simulation...");
}else{
if (JOptionPane.YES_OPTION == result) {
Result2 = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the simulation?", "Are You Sure?", JOptionPane.YES_NO_OPTION);
}
if(JOptionPane.YES_OPTION == Result2){
System.out.println("Maintenance will not be carried out, exiting Simulation...");
try{
System.exit(0);
}
finally{
System.err.println("Exiting...");
System.exit(1);
}
}
if (JOptionPane.NO_OPTION == Result2) {
System.out.println("Continuing simulation...");
}
}}
You need to put else after if(JOptionPane.NO_OPTION == result)
if(main.equalsIgnoreCase("N") | main.equalsIgnoreCase("NO")) is using the bitwise inclusive OR operator "|". Try using the logical OR operator "||" instead:
if(main.equalsIgnoreCase("N") || main.equalsIgnoreCase("NO")){

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();
}

Password prompt and calling a method from an if statement

this i my first attempt at asking a question so hopefully it shows correctly. Basically what I need the program to do is to ask the user for a preset account number and password and only allow them 3 attempts. I then want to call up another method when both requirements are met so i can continue with the program. The first problem i have is that when i enter the correct password its is still showing as incorrect and i don't know why, then i would like to know if i have call the method within the if statement correctly. Thanks.
import java.util.Scanner;
public class Part4 {
public static void main(String[] args)
{
String password = "password", passwordattempt = null;
int accnum = 123456789, acctry = 0, tries = 0;
Scanner input = new Scanner (System.in);
while (acctry != accnum){
System.out.println("\nPlease enter your account number");
acctry = input.nextInt();
if (acctry != accnum)
System.out.print("That number is incorrect. Please try again.");
else
if (acctry == accnum)
{
while (tries < 3)
{
System.out.println("\nPlease enter password");
passwordattempt = input.next();
if (passwordattempt != password){
System.out.print("That password is incorrect");
tries++;
}
else
if (passwordattempt == password){
System.out.print("That is correct");
AccountDetails.Details(args);
}
}
System.out.print("\nYou have exceeded the ammount of tries");
}
}
}
public static class AccountDetails {
private static void Details(String[] args){
System.out.print("it works");
}
}
}
two problems.
1: You're executing your while loop regardless of if it is successful or not.
.
while(tries < 3)
should be
while(tries < 3 && !successfulPassword)
You'll need to add the successfulPassword variable, so that you don't get it right the first time and yet continue to have to enter passwords.
2: Your comparison of strings is grossly, umm, well, wrong. There's two things that catch my eye. The first is you can't use == and != and get the results you expect. You must use .equals(). Secondly, you don't need to repeat the opposite clause like you do with a human. For example, I tell my daughter "If you eat your supper, then you may have cookies. Else, if you do not eat your supper, then you may not have cookies." To a computer, you don't need that last "if you do not eat your supper". It's guaranteed to be true (since you're in the else block anyway) and it just clutters it up. So that just becomes
.
if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}
In the Java language, Strings are objects, and thus comparing them using '==' is testing by reference, and not by equality.
I believe what you are looking for is
if (passwordattempt.equals(password)) {
Check here for more information:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object)

Categories