相同的代码不能用于不同的方法吗?

时间:2017-05-19 06:40:05

标签: java swing numberformatexception

我正在尝试创建一个类,它将创建一个简单的窗口并将数据提供给' Main'类。

public class Input extends JFrame{

int catch_catcher=1;
private JTextField i1;
private JTextField i2;
private JTextField i3;
private JTextField i4;
private JButton ok;
private GridLayout layout;
public Input(){

    super("Input Window");
    setLayout(new FlowLayout());
    i1 =new JTextField("Enter the number of row 1st Mat.",20);
    i2 =new JTextField("Enter the number of column 1st Mat.",20);
    i3 =new JTextField("Enter the number of row 2nd Mat.",20);
    i4 =new JTextField("Enter the number of  column 2nd Mat.",20);
    ok = new JButton("OKay");
    add(i1);
    add(i2);
    add(i3);
    add(i4);
    add(ok);
    ok.addActionListener(
                new ActionListener(){

                public void actionPerformed(ActionEvent e) {
                        if(i1.equals("Enter the number of row 1st Mat.") || i2.equals("Enter the number of column 1st Mat.") || i3.equals("Enter the number of row 2nd Mat.") || i4.equals("Enter the number of  column 2nd Mat.") ){
                            JOptionPane.showMessageDialog(null,"Warning","Please prvude required data",JOptionPane.PLAIN_MESSAGE);
                        }
                        try{
                            int chk = Integer.parseInt(i1.getText());
                            int chk2 = Integer.parseInt(i2.getText());
                            int chk3 = Integer.parseInt(i3.getText());
                            int chk4 = Integer.parseInt(i4.getText());
                            System.out.println("Sucessful");
                        }catch(Exception execpt){
                            JOptionPane.showMessageDialog(null, "Warning", "Please Enter valid String", JOptionPane.PLAIN_MESSAGE);
                            catch_catcher=0;
                        }

                        if(catch_catcher==1){
                            Main Obj=new Main();
                            Obj.getVals();
                            Obj.calculate();
                        }
                    }




                }
            );


}
int get1(){
    return Integer.parseInt(i1.getText()); //this is the line 
}
int get2(){
    return Integer.parseInt(i2.getText()); 
}
int get3(){
    return Integer.parseInt(i3.getText()); 
}
int get4(){
    return Integer.parseInt(i4.getText()); 
}
}

在actionPerformed中的try-catch块中,您可以看到我已经初始化了4个变量,以确保如果在JTextField中输入的数据是String,它将调用catch,并且如果(在try-catch之后)语句将不会运行。我还有一个System.out.println()来查看try块是否已完全执行。它打印"成功"表明我可以在下面的方法中使用这些代码。(或者我错了?尽管有错误,尝试阻止执行吗?)。但问题是方法get1()中存在错误; 。 此方法调用为:

public void getVals(){
    Input in = new Input();
    d1 = in.get1();
    d2 = in.get2();
    d3 = in.get3();
    d4 = in.get4();
}

错误说:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException:     
For input string: "Enter the number of row 1st Mat."
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at main.Input.get1(Input.java:70)
at main.Main.getVals(Main.java:19)
at main.Input$1.actionPerformed(Input.java:56)

弹出窗口。我输入了一些数值。所有数值都是3。一旦我按下确定按钮,就会弹出错误。

主类的代码:

import javax.swing.JFrame;
public class Main {
private int d1;
private int d2;
private int d3;
private int d4;
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
    Input inpt = new Input(); 
    inpt.setVisible(true);
    inpt.setSize(450, 450);
    inpt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void getVals(){
    Input in = new Input();
    d1 = in.get1();
    d2 = in.get2();
    d3 = in.get3();
    d4 = in.get4();
}
/*public void calculate(){
    if (d2 == d3) {
        int[][] MatA = new int[d1][d2];
        for (int i = 0; i < d1; i++) {
            for (int j = 0; j < d2; j++) {
                System.out.printf(" Enter [%d,%d]th element of first matrix", i + 1, j + 1);
                MatA[i][j] = input.nextInt();
            }
        }
        int[][] MatB = new int[d3][d4];
        for (int i = 0; i < d3; i++) {
            for (int j = 0; j < d4; j++) {
                System.out.printf(" Enter [%d,%d]th element of second matrix", i + 1, j + 1);
                MatB[i][j] = input.nextInt();
            }
        }
        int newM[][] = new int[d1][d4];
        int y;
        for (int x = 0; x < d1; x++) {
            y = 0;
            int a = 0;
            while (y < d4) {
                if (a < d2) {
                    newM[x][y] += MatA[x][a] * MatB[a][y];
                    a++;
                } else {
                    y++;
                    a=0;
                }
            }
        }
        for (int a[] : newM) {
            for (int b : a) {
                System.out.printf("%d \n", b);
            }}
        }else{
            System.out.println("Sorry Multiplication not possible ! Dimention error !");
        }
        endstopper();
    }
    public static void endstopper(){
        Scanner input = new Scanner(System.in);
        input.nextLine();
    }*/
}

我已经评论了计算块原因仍然没有被调用。我没有删除Scanner,因为它是在干运行中使用的。

2 个答案:

答案 0 :(得分:2)

您的Main正在创建Input的新实例,这意味着所有文本字段都会显示提示文字。

public void getVals(){
    Input in = new Input();
    d1 = in.get1();
    d2 = in.get2();
    d3 = in.get3();
    d4 = in.get4();
}

屏幕上的实例与您在此方法中创建的实例无关。

相反,将值传递给方法

public void getVals(int value1, int value2, int value3, int value4){
    d1 = value1;
    d2 = value2;
    d3 = value3;
    d4 = value4;
}


try {
    int chk = Integer.parseInt(i1.getText());
    int chk2 = Integer.parseInt(i2.getText());
    int chk3 = Integer.parseInt(i3.getText());
    int chk4 = Integer.parseInt(i4.getText());
    System.out.println("Sucessful");

    Main Obj=new Main();
    Obj.getVals(chk, chk2, chk3, chk4);
    Obj.calculate();
} catch (Exception execpt) {
    JOptionPane.showMessageDialog(null, "Warning", "Please Enter valid String", JOptionPane.PLAIN_MESSAGE);
}

答案 1 :(得分:0)

这是因为您正在从输入中解析整个文本,而不仅仅是用户输入的数字,将输入的提示文本放入例如。另外,tittledBorder需要一些重构才能使它工作:

输入类现在是一个JDialog,它等待用户在尝试读取输入的值之前按下ok按钮。你也从一个输入这些数字的新实例中获取了数据,我也纠正了这个,这个程序现在应该可以工作了 - 至少它在我的机器上完成了:)

import java.util.Scanner;

public class Main {
    private int d1;
    private int d2;
    private int d3;
    private int d4;
    Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        new Main().getVals();
    }

    public void getVals() {
        Input in = new Input();
        in.setModal(true);
        in.setTitle("Input Window");
        in.setSize(300, 300);
        in.setVisible(true);
        d1 = in.get1();
        d2 = in.get2();
        d3 = in.get3();
        d4 = in.get4();
        calculate();
    }

    public void calculate() {
        if (d2 == d3) {
            int[][] MatA = new int[d1][d2];
            for (int i = 0; i < d1; i++) {
                for (int j = 0; j < d2; j++) {
                    System.out.printf(" Enter [%d,%d]th element of first matrix", i + 1, j + 1);
                    MatA[i][j] = input.nextInt();
                }
            }
            int[][] MatB = new int[d3][d4];
            for (int i = 0; i < d3; i++) {
                for (int j = 0; j < d4; j++) {
                    System.out.printf(" Enter [%d,%d]th element of second matrix", i + 1, j + 1);
                    MatB[i][j] = input.nextInt();
                }
            }
            int newM[][] = new int[d1][d4];
            int y;
            for (int x = 0; x < d1; x++) {
                y = 0;
                int a = 0;
                while (y < d4) {
                    if (a < d2) {
                        newM[x][y] += MatA[x][a] * MatB[a][y];
                        a++;
                    } else {
                        y++;
                        a = 0;
                    }
                }
            }
            for (int a[] : newM) {
                for (int b : a) {
                    System.out.printf("%d \n", b);
                }
            }
        } else {
            System.out.println("Sorry Multiplication not possible ! Dimention error !");
        }
        endstopper();
    }

    public static void endstopper() {
        Scanner input = new Scanner(System.in);
        input.nextLine();
    }
}

和输入类:

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

public class Input extends JDialog {

    int catch_catcher = 1;
    private JTextField i1;
    private JTextField i2;
    private JTextField i3;
    private JTextField i4;
    private JButton ok;
    private GridLayout layout;

    public Input() {
        super();
        // super("Input Window");
        setLayout(new FlowLayout());
        i1 = new JTextField(20);
        i1.setBorder(new TitledBorder("Enter the number of row 1st Mat."));
        i2 = new JTextField(20);
        i2.setBorder(new TitledBorder("Enter the number of column 1st Mat."));
        i3 = new JTextField(20);
        i3.setBorder(new TitledBorder("Enter the number of row 2nd Mat."));
        i4 = new JTextField(20);
        i4.setBorder(new TitledBorder("Enter the number of  column 2nd Mat."));
        ok = new JButton("OKay");
        add(i1);
        add(i2);
        add(i3);
        add(i4);
        add(ok);
        ok.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (i1.equals("Enter the number of row 1st Mat.") || i2.equals("Enter the number of column 1st Mat.")
                        || i3.equals("Enter the number of row 2nd Mat.")
                        || i4.equals("Enter the number of  column 2nd Mat.")) {
                    JOptionPane.showMessageDialog(null, "Warning", "Please prvude required data",
                            JOptionPane.PLAIN_MESSAGE);
                }
                setVisible(false);
            }

        });

    }

    int get1() {
        return Integer.parseInt(i1.getText()); // this is the line
    }

    int get2() {
        return Integer.parseInt(i2.getText());
    }

    int get3() {
        return Integer.parseInt(i3.getText());
    }

    int get4() {
        return Integer.parseInt(i4.getText());
    }
}

同样最好将输入字段重新定义为仅接受数字值,有完整的答案如何在SO上执行此操作:Is there any way to accept only numeric values in a JTextField?