通过GUI进行java输入输出测试
大家好,请告诉我在尝试运行此程序并获得通过GUI进行java输入输出测试,java,swing,java-8,java-7,Java,Swing,Java 8,Java 7,大家好,请告诉我在尝试运行此程序并获得java.lang.NumberFormatException错误时我错在哪里 import javax.swing.*; public class InputOutputTest { public static void main(String[] args) { //takes input through GUI String input = JOptionPane.showInputDialog("Enternumber");
java.lang.NumberFormatException
错误时我错在哪里
import javax.swing.*;
public class InputOutputTest {
public static void main(String[] args) {
//takes input through GUI
String input = JOptionPane.showInputDialog("Enternumber");
int number = Integer.parseInt(input);
int square = number * number;
//Display square on console
System.out.println("square:" + square);
//Display square on GUI
JOptionPane.showMessageDialog(null, "square:"+ square);
System.exit(0);
}
}
您应该在“输入”对话框中只输入数字。parseInt导致异常。添加错误处理,如下所示
String input = JOptionPane.showInputDialog("Enter number");
try {
int number = Integer.parseInt(input);
int square = number * number;
System.out.println("square:" + square);
JOptionPane.showMessageDialog(null, "square:" + square);
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Only Numbers are accepted");
}
在
输入对话框
中输入数字。它不能包含任何字母或符号字符。