This is the GUI form that I have created. The value is obtained from the text field and it is stored in the new variable. For some value, it needs to be converted into the integer type. I have converted the value to the integer type, but I am trying to handle the exception when the user doesn't enter any value in the text field. for that, I have used if statement. And for the next exception is when the user enters the string value into the integer field. So I am not been able to handle this exception properly. please help me in doing so.
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if( plat==("") || name==("") || hours==("")|| period==("")|| salary==
("")){
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(ArithmeticException e){
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
First of all you cannot compare Strings like that. Use equals method or isEmpty() to check if String is empty. Second thing is that if String is not parsable to Integer it throws NumberFormatException not an ArithmeticException according to documentation:
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if(plat.isEmpty() || name.isEmpty() || hours.isEmpty() || period.isEmpty()|| salary.isEmpty()) { // changed String comparison
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(NumberFormatExceptione){ // Changed exception type
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
It is never advisable to do like this
plat==("")
do it like this
StringUtils.isEmpty(plat)
and instead of putting integer parsing under try catch you can avoid it with
StringUtils.isNumeric(hours)
and if this condition comes out to false you can take the required action.
Note : StringUtils is available under import apache.commons.lang3
Related
This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 3 years ago.
How can I make my setter method public void setYear(String year) check if the input is a number or not? It's for a class exercise. I'm just trying to understand why/how to do this. I don't know why, but it has to be string year, and I need to make sure that only a number can be used.
For example I have:
public void setColour(String colour) {
colour = colour;
}
public void setYear(String year) {
if (Integer.parseInt(year) >= 0) {
//Do stuff here
}
}
Use Integer.parseInt(String s) to check if String year can be convert to an Integer greater or equal to zero (logically, a year can not be negative). If the input can not be converted to an Integer, it will throw a NumberFormatException.
I can propose 2 ways of doing this.
Suppose the string you need to validate is strYear and you consider valid all integer values >= 0.
The 1st is by forcing the string to be casted to an integer and catching any error thrown:
int year = -1;
try {
year = Integer.parseInt(strYear);
} catch (NumberFormatException e) {
e.printStackTrace();
}
boolean validYear = (year >= 0);
The 2nd is eliminating all non numeric chars in the string and compare the result to the original string. If they are the same then the string consists only of digits:
strYear = strYear.trim();
String strOnlyDigits = strYear.replaceAll("\\D", "");
boolean validYear = (!strYear.isEmpty() && strYear.equals(strOnlyDigits));
public int year;
public void setYear(String year){
try {
year = Integer.parseInt(year);
} catch(Exception e) {
e.printStackTrace();
}
}
You can use try and catch to check if the input is a number. In here, you are trying to parse the String into integer. If it only contains a number, it will be able to convert it successfully. On the other hand, if it has some other characters, it will stop and you will get an exception. Try and catch prevents your program from crashing.
At the same time, you can try regular expression to check if it only contains number.
String regex = "[0-9]+";
year.matches(regex );
I have made an app where the user selects a food type, enters a weight and then the app calculates the calories. This calorie is then moved onto the MainActivity (when the 'Save' button is pressed) where the total calories will be displayed for that day.
I need the app to take all calories calculated and add them onto any existing values on the main activity. I wrote the code below, however the app crashes when I press the save button my second activity.
String greeting = getIntent().getStringExtra("Greeting Message");
EditText editText1 = (EditText)findViewById(R.id.editText1);
String value = editText1.getText().toString();
Integer aValue = (value != null && !value.isEmpty()) ? Integer.parseInt(value) : 0 ;
Integer bValue = (greeting != null && !greeting.isEmpty()) ? count +=Integer.parseInt(greeting) : 0 ;
editText1.setText(count + "");
Stack Error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nicola.student.mealtracker/com.nicola.student.mealtracker.MainActivity}: java.lang.NumberFormatException: Invalid int: "70.0Cal"
You should check Your value String, Your exception tells me that the String is "70.0Cal". First, You can get a substring, if You know that the last three signs are allways "Cal"
String value = value.substring(0,substring.length()-3);
and second, You have a decimal value, so You should use not integer, You should use Float or double.
also, You should check if the text in the EditText is not null or empty:
String edittextText = editText1.getText().toString();
if(edittextText!=null && !edittextText.equals("")){
//start calculating
}
Either value, or greeting has a value that cannot be converted to int : "70.0Cal".
So remove the suffic "Cal" , and if you have to deal with fractions, use double instead of int.
Looking at the short stack trace provided I can see that you are parsing a String value that is not in a correct Integer format.
You will have to do some validation on the field to make sure that the input provided is a valid numeric value. You can do that by using the following method or by setting the EditText inputType android:inputType="number"
/**
* Checks if the text is a valid numeric value
* #param value
* #return valid
*/
public static boolean isNumeric(String value) {
if (!isNull(value)) {
if (value.matches("[-+]?\\d*\\.?\\d+")) {
return true;
}
}
return false;
}
I would suggest not appending Cal to the value returned. Keep the input numeric. Rather add the "Cal" value in a TextView next to your EditText.
Implement it this way by using the isNumeric method to check the value before parsing.
public void executeYourCode() {
//Parse your values to Double
//as you are using Double values
Double aValue = getCheckedValue(value) ;
Double bValue = getCheckedValue(greeting);
count+= bValue;
editText1.setText(String.valueOf(count));
}
public int getCheckedValue(String value) {
if (value != null && !value.isEmpty() && isNumeric(value)) {
return Double.parseDouble(value.trim());
}
return 0;
}
Stuck on attempting to convert a String to an Integer. I'm using libgdx & I've tried a few mothods of doing it & I keep getting null in return.
Here is my most recent method I've tried also the easiest.
String x = textfield_1.getText();
String y = textfield_2.getText();
Integer integerfield_1 = Integer.getInteger(textfield_1.getText(), null);
if (integerfield_1 == null) {
System.out.println("Incorrect Integer (Integer Only)");
} else {
System.out.println("Please Enter The Position");
//TODO Fill GUI Form.
}
Anyone have any tips?
Take a look at the JavaDocs for Integer.getInteger(String, Integer) for a sec
Returns: the Integer value of the property.
Or in longer terms...
Returns the integer value of the system property with the specified
name. The first argument is treated as the name of a system property.
System properties are accessible through the
System.getProperty(java.lang.String) method. The string value of this
property is then interpreted as an integer value, as per the
Integer.decode method, and an Integer object representing this value
is returned.
If the property value begins with the two ASCII characters 0x or the ASCII character #, not followed by a minus sign, then the rest of
it is parsed as a hexadecimal integer exactly as by the method
valueOf(java.lang.String, int) with radix 16.
If the property value begins with the ASCII character 0 followed by another character, it is parsed as an octal integer exactly as by the
method valueOf(java.lang.String, int) with radix 8.
Otherwise, the property value is parsed as a decimal integer exactly as by the method valueOf(java.lang.String, int) with radix
10.
The second argument is the default value. The default value is
returned if there is no property of the specified name, if the
property does not have the correct numeric format, or if the specified
name is empty or null.
This is not doing what you think it is...
Instead you should be using Integer.parseInt(String), this will throw a NumberFormatException when the value of the String can't be converted to a valid integer...
For example...
String x = textfield_1.getText();
String y = textfield_2.getText();
try {
Integer integerfield_1 = Integer.parseInt(textfield_1.getText());
System.out.println("Please Enter The Position");
//TODO Fill GUI Form.
} catch (NumberFormatException exp) {
exp.printStackTrace();
System.out.println("Incorrect Integer (Integer Only)");
}
If I understand you, then this
Integer integerfield_1 = Integer.getInteger(textfield_1.getText(), null);
Should be something like Integer.parseInt(String) this -
int integerfield_1 = 0;
try {
integerfield_1 = (x != null) ? Integer.parseInt(x.trim()) : 0;
} catch (NumberFormatException e) {
e.printStackTrace();
}
If you really want to use Integer (the wrapper), then you could use Integer.valueOf(String).
Integer integerfield_1 = null;
try {
integerfield_1 = (x != null) ? Integer.valueOf(x.trim()) : null;
} catch (NumberFormatException e) {
e.printStackTrace();
}
I'm making a GUI program. In my first program I have the following code:
double num1;
num1 = Double.parseDouble(guess.getText());
I believe that this code gets the value from the text field and converts it to double.
How can I get the value and convert it to String or Char?
Since the getText() already returns a String, storing its value as a String is trivial.
In order to parse a double, you've already done it, just watch for the NumberFormatException, in case of invalid input.
To store its value as a char, that depends on your requirements. Do you want the first character? Do you require the string to have only a single character? Is any character valid? And so on.
// Storing the value as a String.
String value = guess.getText();
// Storing the value as a double.
double doubleValue;
try {
doubleValue = Double.parseDouble(value);
} catch (NumberFormatException e) {
// Invalid double String.
}
// Storing the value as a char.
char firstChar = value.length() > 0 ? value.charAt(0) : (char) 0;
// Require the String to have exactly one character.
if (value.length() != 1) {
// Error state.
}
char charValue = value.charAt(0);
use String.valueOf() instead of Double.parseDouble() this will help you convert double into string value
The getText() already returns the text as String.
Btw, be careful of Exceptions due to parse error. But your on the right track. :)
The getText()method returns a String. when you use .parseDouble what you are really doing is turning the string the user entered and into a double therefore in the case of a string you do not have to use a .parse method because the value called is already a string. In the case of a character you would have to use something like this:
String text = jTextField1.getText();
if (text.length() > 1 && !text.contains(" ") && !text.contains(",")) {
//make sure that its length is not over 1, and that it has no spaces and no commas
char ch = text;
} else {
//if a space or comma was found no matter how big the text it will execute the else..
System.out.println("this is not allowed");
jTextField1.setText("");
}
The getText() function already fetches a String value from the Textfield.
For example:
String var = guess.getText();
Here, var is storing the String value received from the Textfield.
I've been working this for 2 days but I can't still figure how to check if the jtextfield is empty (Double not String) before passing it to my database.
I figured it out how to validate String if the field is empty, but I need to put the right code on how to validate Double if the field is empty.
Thanks in advance.
Here's my code:
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
String inventnamef = inventNameField.getText();
String categ = cmbname.getSelectedItem().toString();
double inventreorderf = Double.parseDouble(inventReorderField.getText());
..............
if ((inventCodeField.trim().Length()==0) || (inventNameField.trim().Length()==0)
To enforce formatting (numeric etc) you can use JFormattedTextField.
To ensure values are not blank see No blanks in JTextField
You are reading the double at first as a String. So, you can do something like this:
double inventreorderf;
if (inventReorderField.getText().trim().length == 0)
{
//Do something which should happen when the field is empty
}
else
{
try
{
inventreorderf = Double.parseDouble(inventReorderField.getText());
}
catch (Exception e)
{
//The user has entered an invalid number. Notify him/her here.
}
}