name = full_name_input.getText();
Fname = father_name_input.getText();
cnic = father_cnic_input.getText();
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
prsnt_add = present_add_input.getText();
city = city_input.getText();
province = radio_text;
if(name.equals("") || Fname.equals("") || cnic.equals("") || DOB==0 || Class_V==0 || prsnt_add.equals("") || city.equals("") || province.equals(""))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
radio_text here is actually input from radio button and it is giving an error
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
actually i want to ensure that none of the jfields remain empty by the user
and if any field remains undefined it shows a popup please fill all fields
but when date of birth or class field or both remain unfiilled by the user it gives an error mentioned in the preeceding paragraph
What's happening is you're checking your fields after you try to set them, but the error occurs before that. For example, if DOB_input's text is "", DOB will throw an error trying to parse that (Integer.parseInt() can't deal with strings like that) before you see that it's empty. If you want to keep your if-statement, you'll have to move it above the lines where you set your values. However, to do that you'd need to tweak it a bit so you check the jfields' values. Like:
if(full_name_input.getText().equals("") || father_name_input.getText().equals("") ..... )
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
I bet you have a problem here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
Either DOB_input or class_input (or even both of them) getText() returns empty string. You should catch that exception and properly handle it like this:
try {
value = Integer.parseInt(input.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Illegal nuber format for field <field>");
return;
}
There is a problem with parsing number from String.
Did you check on which line this happened?
I suppose that here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
Related
I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).
private void searchProduct()
{
try {
Product p = new Product();
//Read data
p.setId(Double.parseDouble(textID.getText()));
//Display data
textDescription.setText(String.valueOf(p.getDescription()));
textPrice.setText(String.valueOf(p.getUnitPrice()));
textUOM.setText(String.valueOf(p.getUnitOfMeasurement()));
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(this.frame, "ID must be number", "Error",JOptionPane.ERROR_MESSAGE);
}
}
Hello recently I tried to put a button "Search" to find a product than equals to ID, but I don't know how to parse the ID than comes from the product class, I have a error.
Does the textID.getText() actually is a parseable double string? For instance "10.1" do but "10.1 " no.
Always I did this kind of conversion I use trim() to remove this extra white spaces as follow:
String stringValue = textID.getText();
if(stringValue != null) {
stringValue = stringValue.trim();
}
double doubleValue = Double.parseDouble(stringValue);
Se here http://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String- how to avoid NumberFormatException using a regular expression to text you string before try to convert it to double.
I'm attempting to add an ArrayList to an object with a do...while loop. Unfortunately I continue to get a validation error each time I run the program.
Here is the function that I am using to add an ArrayList to the object DVD:
public DVD getNewDVDInfo() {
String title = io.readString("Please enter DVD title");
String releaseDate = io.readString("Please enter Release Date (mm-DD-yyyy)");
LocalDate ld = LocalDate.parse(releaseDate, DateTimeFormatter.ofPattern("mm-DD-yyyy"));
String mpaaRating = io.readString("Please enter MPAA Rating");
String directorName = io.readString("Please enter Director's Name");
String studio = io.readString("Please enter Studio");
boolean hasNext = true;
ArrayList<String> userRating = new ArrayList<>();
String userRatingString = io.readString("Please enter User Rating");
userRating.add(userRatingString);
DVD currentDVD = new DVD(title);
currentDVD.setReleaseDate(ld);
currentDVD.setMpaaRating(mpaaRating);
currentDVD.setDirectorName(directorName);
currentDVD.setStudio(studio);
currentDVD.setUserRating(userRating);
return currentDVD;
}
The validation method:
private void validateDVDData(DVD dvd) throws DVDLibraryDataValidationException {
if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0
|| dvd.getReleaseDate() == null
|| dvd.getMpaaRating() == null || dvd.getMpaaRating().trim().length() == 0
|| dvd.getDirectorName() == null || dvd.getDirectorName().trim().length() == 0
|| dvd.getStudio() == null || dvd.getStudio().trim().length() == 0
|| dvd.getUserRating()== null || dvd.getUserRating().isEmpty()); {
throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required");
}
}
Every time I run the app, the error message is thrown.
Any help would be much appreciated.
To identify your problem you could use a debugger but you could also improve the way of doing the check.
Instead of doing a global error :
ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name,
Studio, User Rating] are required");
it would be more helpful to the user (and also to you for tracing the information) to know where is exactly the problem in the provided values.
In your DVDLibraryDataValidationException class, you could add a List of String field where you add the error field names.
And you could override getMessage() of this class to provide a helpful message indicating the fields with validation error.
Just to give an idea on the way to start :
List<String> errorFields = new ArrayList<>();
if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0){
errorFields.add("title");
}
if (dvd.getReleaseDate() == null ){
errorFields.add("release date");
}
...
if (!errorFields.isEmpty()){
throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required",
errorFields);
}
My code:
name = jTextFieldName.getText();
admin = Integer.parseInt(jTextFieldAdmin.getText());
anal = Integer.parseInt(jTextFieldAnalytical.getText());
creat = Integer.parseInt(jTextFieldCreative.getText());
finish = Integer.parseInt(jTextFieldFinisher.getText());
persons.addPerson(name, admin, anal, creat, finish);
persons.savePersons();
I want to make sure that name is a string and that admin, anal, creat and finish are ints between 0 and 30. I'm thinking that I should use try-catch, but I don't know exactly how to use it in this context. Any help appreciated!
try catch isn't a bad way to handle this:
try {
name = jTextFieldName.getText();
admin = Integer.parseInt(jTextFieldAdmin.getText());
anal = Integer.parseInt(jTextFieldAnalytical.getText());
creat = Integer.parseInt(jTextFieldCreative.getText());
finish = Integer.parseInt(jTextFieldFinisher.getText());
persons.addPerson(name, admin, anal, creat, finish);
persons.savePersons();
} catch (NumberFormatException e) {
// One of the integer fields failed to parse. Do something to alert the user.
}
You can then also put some bounds checking in the try part. e.g.
if (admin < 0 || admin > 30) {
// Problem. Alert the user.
}
Why don't you use a JSpinner instead.
What you need is if-else which statisfies condition or ask user to input again if required.
ex -
if(admin<0 || admin>30){
// ask user to input again.
}
Use InputVerifier for JTextField, like below
public class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
// Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false
}
}
// Set input verifier to the text field
jTextField.setInputVerifier(new MyInputVerifier());
i have an xml file with attributes like this:
<folder name = 'somename' description = ''/>
i want to display the description attribute as 'null' but it force closes and throws a FATAL Exception main in the LogCat.
i have this code below at the startElement() method
if (localName.equalsIgnoreCase("folder")) {
/** Get attribute value */
if(attributes.getValue("description")== "null"){
parseList.setFolderdesc(null);
}else{
String desc = attributes.getValue("description");
parseList.setFolderdesc(desc);
}
i tried this code but no luck...
how will i solve this without changing my xml file?
try with the following code
String desc = null;
try{
desc = attributes.getValue("description");
if((desc == null) || (desc.length()<=0)){
desc = null;
}
}catch(Exception ex){
desc = null;
}
if(parseList != null){
parseList.setFolderdesc(desc);
}
This code doesn't do what you expect:
if (attributes.getValue("description") == "null") {
You are comparing the attribute value with the String "null" not with a java null. (And you are testing strings the unsafe way too! Strings should be tested for equality using String.equals() not the == operator.)
That test should be written as follows:
if (attributes.getValue("description") == null) {
or better still:
if (attributes.getValue("description") == null ||
attributes.getValue("description").isEmpty()) {
(I'm not sure whether this will fix you problem, because I don't understand your problem description.)