我想要求用户在showInputDialog中输入整数,但如果输入是非整数值,则catch将起作用。
有人能引导我走向正确的方向吗?
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 :(得分:1)
如果你读过JavaDocs for JOptionPane.showInputDialog
,你就会看到......
返回:
用户的输入,或null表示用户取消了输入
这意味着您可以将从方法调用返回的结果分配给变量,例如......
String text = JOptionPane.showInputDialog(null, "Enter your number");
有关详细信息,请参阅How to Make Dialogs和JavaDocs for JOptionpane
答案 1 :(得分:0)
以下是示例
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);
} }