Hot questions for Using JTextField in parsing

Question:

So I have this to convert String from JTextField to int. It says Exception in thread "main" java.lang.NumberFormatException: For input string: "". Please help.

 JTextField amountfld = new JTextField(15);
 gbc.gridx = 1; // Probably not affecting anything
 gbc.gridy = 3; //
 add(amountfld, gbc);
 String amountString = amountfld.getText();
 int amount = Integer.parseInt(amountString);

Answer:

From docs:

Throws: NumberFormatException - if the string does not contain a parsable integer.

The empty String "" is not a parsable integer, so your code will always produce a NumberFormatException if no value is entered.

There are many ways in which you can avoid this. You can simply check if the String value you got from amountField.getText() is actually populated. You can create a custom IntegerField, which only allows integers as input, but adding Document to a JTextField. Create a Document to only allow integers an input:

public static class IntegerDocument extends PlainDocument {

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        StringBuilder sb = new StringBuilder(str.length());
        for (char c:str.toCharArray()) {
            if (!Character.isDigit(c)) {
                sb.append(c);
            }
        }
        super.insertString(offs, sb.toString(), a);
    }
}

Now create a IntergerField with a convenient getInt method, which returns zero if nothing is entered:

public static class IntegerField extends JTextField {
    public IntegerField(String txt) {
        super(txt);
        setDocument(new IntegerDocument());
    }

    public int getInt() {
        return this.getText().equals("") ? 0 : Integer.parseInt(this.getText());        
    }
}

Now you can retrieve the integer value from amountField without doing any checks:

JTextField amountField = new IntegerField("15");
...
//amount will be zero if nothing is entered
int amount = amountField.getInt();

Question:

On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"

Answer:

You are not reading your file line by line. What you are actually supposed to do is get a line, split it, remove the double quotes and compare to your string. Or you can wrap your input string in a double quote and just compare with the string after splitting. For this try the following code:

Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));

  String s1 = null;
  String id= null;
  String[] tempArr = null;
  String searchStr = "\""+search_field.getText()+"\"";
  System.out.print("searchStr = " + searchStr );

  while(scanner.hasNext()) { // While there are more lines in file 
    s1= scanner.nextLine();
    tempArr = s1.split(","); // use coma_delimiter instead coma_delimiter if coma_delimiter=","
    id = (tempArr != null && tempArr.length > 0? tempArr[0] : null);
    System.out.print("ID = " + id);

    if(id != null && id.equals(searchStr)) {
      System.out.print("OKOK");
      break; // quit the loop searchStr is found
    } else {
    System.out.println("NOK");
    }
  }
} catch (FileNotFoundException fe) {
 fe.printStackTrace();
} finally {
  scanner.close();
}

Question:

Currently Having my fields like that:

 final JTextField PID = new JTextField("Product ID", 7);
 frame.getContentPane().add(PID);

My method:

public StockItem(Long id, String name, String desc, double price) {
    this.id = id;
    this.name = name;
    this.description = desc;
    this.price = price;
}   

Trying to use this method with values from my JTextFields, but it does not allow to use JTextFields under my Long/String/double places. Is there any way how I could convert my JTextFields into the required things without editing my Method.


Answer:

You should use the text field text and parse it.

long l = Long.parseLong(PID.getText());
double d = Double.parseDouble(PID.getText());