相同的代码不能以不同的方法工作?

Same code not working in a diffrent methods?

我正在尝试制作一个 class,它将创建一个简单的 window 并将数据提供给 'Main' class.

中的变量
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 中输入的数据是字符串,它将调用 catch,而下面的 if(在 try - catch 之后)语句不会运行。我还有一个 System.out.println() 来查看 try 块是否已完全执行。它打印 "Successful" 表明我可以在下面的方法中使用这些代码。(或者我错了吗?尽管有错误,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.actionPerformed(Input.java:56)

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

主要代码 class:

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,因为它被干运行.

这是因为你解析的是Inputs中的整个文本,而不仅仅是用户输入的数字,将输入的提示文本放入eg。 tittledBorder,此外,它需要一些重构才能使其工作:

输入 class 现在是一个 JDialog,在您尝试读取输入的值之前等待用户按下确定按钮。您还从输入这些数字的实例的新实例中获取数据,我也更正了这一点,该程序现在应该可以运行了——至少在我的机器上是这样:)

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();
    }
}

和输入class:

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?

您的 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);
}