How do I accept both integer and string inputs in JOptionPane?

49 views Asked by At

I'm creating a java program where the user has to guess between 1 to 10, in which if they're wrong it'll loop. I need it so they can also input String words into it.

`I haven't tried anything yet since I am still a beginner in java

Here's the code

import javax.swing.JOptionPane;
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    //int numcor;

    while (true) {
      int numcor = Integer.parseInt(JOptionPane.showInputDialog("Enter a number between 1 to          10: "));
      //numcor = input.nextInt();
      if (numcor == 5) {
        JOptionPane.showMessageDialog(null, "Correct number!");
        break;
      } else if (input == null) {
        JOptionPane.showMessageDialog(null, "Goodbye!");
        break;
      } else {
        JOptionPane.showMessageDialog(null, "Try Again");
      }
    }
  }
}
1

There are 1 answers

0
queeg On

Just open a dialog where the user can input some characters. As soon as the user is done, your program starts interpreting the entered characters.

If it can be parsed as an integer, treat it as in integer. Otherwise treat it as text and do the needful.

In code this could look like:

String input = JOptionPane.showInputDialog("Enter a number between 1 to 10: ");
try {
    int numcor = Integer.parseInt(input);
    // treat the number
} catch (NumberFormatException e) {
    // treat input as text
}