1

currently i'm making an attendence software but getting an runtime error here is my code:-

public class gui015 extends JFrame {

private JTextField[] tf;
private JRadioButton a;
private JRadioButton b;
private JTextField t2;
private JOptionPane op;
private JButton c;
public gui015()
{
    super("Attenedence");
    setLayout(new FlowLayout());
    t2 = new JTextField("Enter no. of students");
    add(t2);
    String s = t2.getText();
    int a = Integer.parseInt(s);
    tf = new JTextField[a];
    while(a>0)
    {
        tf[a] = new JTextField();
        add(tf[a]);
    }
}

and i'm getting an bunch of errors like this:-

Exception in thread "main" java.lang.NumberFormatException: For input string: "Enter no. of students"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at tutorial.gui015.<init>(gui015.java:26)
    at tutorial.gui016.main(gui016.java:7)
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Dev Joshi
  • 73
  • 1
  • 1
  • 8
  • @ANS Not a NPE question – Scary Wombat May 01 '17 at 08:46
  • joshi what number do you think should be represented by the String `"Enter no. of students"`? – Scary Wombat May 01 '17 at 08:47
  • 1
    Hint: `new JTextField("Enter no. of students");` fills the `JTextField` with `Enter no. of students`, so that string will not became a label for the text field, it will be the **content** of the text field. – BackSlash May 01 '17 at 08:49
  • @scary wombat the thing is the text field will be displayed and then user will enter a no. Of textfiled to be created – Dev Joshi May 01 '17 at 09:11
  • Wrong approach i would say. Try to learn more about JTextfield class and parseInt of Integer wrapper class. – privatejava May 01 '17 at 09:24
  • 1
    When you are getting the text from the text field in your constructor, the user won’t have time for entering the number before you try parsing it. Your program must wait until the user has typed. You will probably want a way the user can let the program know “I have typed the number now, now create the text fields”. – Ole V.V. May 01 '17 at 09:25
  • One option is rather than the `t2` text field you use `JOptionPane` for prompting the user for the number. – Ole V.V. May 01 '17 at 09:26
  • It’s a better than average question for a new Stackoverflower, BTW. You might improve still by making the intended behaviour clearer and/or pointing out which line in the code is line 26 (where the exception happens). Your [(nearly) Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) is great. – Ole V.V. May 01 '17 at 09:38

0 Answers0