如何将showInputDialog的输入放入变量中?

如何将showInputDialog的输入放入变量中?

问题描述:

我想要求用户在showInputDialog中输入整数,但如果输入是非整数值,那么捕获将工作。如何将showInputDialog的输入放入变量中?

任何人都可以引导我走向正确的方向吗?

public static void tryCatch(){ 
    try{ 
     Scanner scanner = new Scanner(System.in); 
     JOptionPane.showMessageDialog(null, "Welcome"); 
     JOptionPane.showInputDialog(null, "Enter your number"); 

     int pass = Integer.parseInt(null); 

    } catch(InputMismatchException e){ 
     JOptionPane.showMessageDialog(null, "Invalid number!"); 
    } 
} 
+0

'字符串inputString = JOptionPane.showInput ...'。然后解析'inputString' – 2014-09-19 03:33:35

+0

也请确保捕获正确的异常。试图解析无效的整数会给你一个'NumberFormatException' – 2014-09-19 03:35:44

这里是例子

import javax.swing.*; 

/** 
* JOptionPane showInputDialog example #1. 
* A simple showInputDialog example. 
* 
*/ 
public class JOptionPaneShowInputDialogExample1 
{ 
    public static void main(String[] args) 
    { 
    // a jframe here isn't strictly necessary, but it makes the example a little more real 
    JFrame frame = new JFrame("InputDialog Example #1"); 

    // prompt the user to enter their num 
    int num; 

    do { 

     try 
       { 
        num= Integer.parseInt(JOptionPane.showInputDialog(frame, "Enter the  number")); 
        break; 
       } 

       catch (NumberFormatException e) 
       { 
        JOptionPane.showMessageDialog(null, 
          "Error. Please enter a valid number", "Error", 
          JOptionPane.INFORMATION_MESSAGE); 
       } 

    } while (true) 
    // get the user's input. note that if they press Cancel, 'name' will be null 
    System.out.printf("The user's name is '%d'.\n", num); 
    System.exit(0); 

}}

+0

我应该使用什么类型的异常?我试图写字符,但我的例外仍然不起作用 – mazin 2014-09-19 03:38:27

+0

如果您期望的数字,然后赶上NumberFormatException – DeepInJava 2014-09-19 03:40:11

+0

@mazin - 我已编辑我的代码,以套用您的方案与捕获NumberFormatException。我希望它有帮助! – DeepInJava 2014-09-19 03:50:16

如果你有JavaDocs for JOptionPane.showInputDialog的读,你会看到...

返回:
用户的输入,或null表示用户取消输入

这意味着您可以分配从方法调用返回给一个变量,类似的结果...

String text = JOptionPane.showInputDialog(null, "Enter your number"); 

How to Make DialogsJavaDocs for JOptionpane更多细节