As an exercise, I want to create a popup window where user enters a string, what I want to achieve:
- If they enter yes, print YES
- If they enter no, print NO
- If they enter something else, loop until they enter yes or no then print YES or NO
1 and 2 work, 3 will loop but then print nothing after yes or no is entered
any ideas?
package harmony.randomstuff; //imports import java.text.*; import java.util.Scanner; import javax.swing.JOptionPane; public class RandomStuff { public static void main (String[]args) { //objects Scanner dakeyboard = new Scanner(System.in); //************************************************************ String xd = ""; //creates popup window for user to enter something String x = JOptionPane.showInputDialog("enter (yes\no)"); // this will loop until you enter yes or no then stop looping but nothing prints //I tried to express the logic statement "if it is not true that x = yes or x = no then loop until it is if (!(("yes".equals(x))||("no".equals(x)))) { do { x = JOptionPane.showInputDialog("please enter (yes\no)"); } while (!(("yes".equals(x))||("no".equals(x)))); } // the two loops here work perfectly else if ("yes".equals(x)){ xd="YES"; } else if ("no".equals(x)){ xd="NO"; } //************************************************************ System.out.println(xd); //************************************************************ dakeyboard.close(); } }
Advertisement
Answer
the looping is incorrect, instead of else if
you should just use if
right after this comment // the two loops here work perfectly
package org.rj.stackoverflow; import java.text.*; import java.util.Scanner; import javax.swing.JOptionPane; public class RandomStuff { public static void main(String[] args) { //objects Scanner dakeyboard = new Scanner(System.in); //************************************************************ String xd = ""; //creates popup window for user to enter something String x = JOptionPane.showInputDialog("enter (yes\no)"); // this will loop until you enter yes or no then stop looping but nothing prints //I tried to express the logic statement "if it is not true that x = yes or x = no then loop until it is if (!(("yes".equals(x)) || ("no".equals(x)))) { do { x = JOptionPane.showInputDialog("please enter (yes\no)"); } while (!(("yes".equals(x)) || ("no".equals(x)))); } // the two loops here work perfectly if ("yes".equals(x)) { xd = "YES"; } else if ("no".equals(x)) { xd = "NO"; } //************************************************************ System.out.println(xd); //************************************************************ dakeyboard.close(); } }
if you would like to improve code, do below
String x; do { x = JOptionPane.showInputDialog("please enter (yes\no)"); } while(!x.equals("yes") && !x.equals("no")); System.out.println(x.toUpperCase());