java输入输出测试通过GUI

时间:2016-10-01 09:46:07

标签: 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"); 
   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); 
 } 
} 

1 个答案:

答案 0 :(得分:3)

您应该只在输入对话框中输入数字。 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");
        }