-1

I am trying to make a class which will create a simple window and gives data to variables in '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()); 
}
}

At the try-catch block in actionPerformed you can see I have initialized 4 variables to ensure that if the data entered in JTextField is String it will invoke catch and the following if (just after try - catch) statement will not run. And I have also a System.out.println() to see if try block has executed completely. And it prints "Successful" indicating that I can use those code in methods below.(Or am I wrong? Does try block execute completely in spite of error?). But the problem is there's an error in method get1(); . This method is invoked as:

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

the error Says:

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)

The window pops up. I entered some numeric values. All values were 3 to be exact. And as soon as I press ok button error pops up.

code for main 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();
    }*/
}

I have commented the calculate block cause still its not invoked. I have not deleted Scanner because it was used in dry run.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

2 Answers2

1

Your Main is creating a new instance of Input, which means all the text fields are filled with the prompt text.

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

The instance on the screen has nothing to do with the instance you have created in this method.

Instead, pass the values to the method

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);
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • You don't know how the code works, instead of making assumptions and post such answer, you should ask Him to post entire code, then correct what is wrong. – Krzysztof Cichocki May 19 '17 at 07:02
  • @KrzysztofCichocki Please, read the question thoroughly, all the code I've presented here is based on the code presented in the question, there is no assumption - The statement that triggered my answer was *"And it prints "Successful" indicating that I can use those code in methods below"* – MadProgrammer May 19 '17 at 07:06
  • @KrzysztofCichocki Read the code snippet right above *"the error Says:"* - The OP has presented the exact code which is causing there issue – MadProgrammer May 19 '17 at 07:08
  • @KrzysztofCichocki And then read the last code snippet in the question - Then tell me I'm assuming anything ... – MadProgrammer May 19 '17 at 07:08
  • I works. But I still don't understand why my code failed.? – Eric Domanic May 19 '17 at 07:14
  • @EricDomanic You create a brand new instance of `Input` - this is a new object, there is no relationship between it and the version you created in `main`, which is the version which is on the screen, holding your numbers – MadProgrammer May 19 '17 at 07:16
  • @MadProgrammer Still you have repeated Input in = new Input(); in getVals, which is obviously wrong. – Krzysztof Cichocki May 19 '17 at 07:23
  • @KrzysztofCichocki Opps, copy and paste - but I never used it ;) – MadProgrammer May 19 '17 at 07:28
0

It is because you are parsing the entire text from Inputs, not just the number entered by user, put the prompt text for the input into eg. tittledBorder, additionally, it needed some refactoring to make it work:

The input class is a JDialog now, which waits for the user to press the ok button before you try to read the entered values. Also you were getting the data from a new instance instaed of the one in which these numbers were entered, I've corrected this as well, this program should work now - at least it did on my machine :)

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

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

Also it would be best to restirct the input fields to accept only numeric values, there is complete answer how to do that here on SO: Is there any way to accept only numeric values in a JTextField?

Community
  • 1
  • 1
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
  • Your answer will generate a `Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""` - All the information you need to understand the problem is presented in the question, but you need to be prepared to read through it – MadProgrammer May 19 '17 at 07:07
  • *"Also you were getting the data from a new instance instaed of the one in which these numbers were entered"* - Oh really, you don't say – MadProgrammer May 19 '17 at 07:18