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();
}
Related
I primarily code in Python and I am completely new to java, so I am having difficulty with a simple programming task in Java regarding parsing through a .csv file. My .csv file has multiple columns and I want to parse through each line and store the second column as a string and the last column (column 4) as a double as a (string, double) pair. However, if column four does not contain a value that can be cast as a double value, I would like to assign a 0.0 as the double in the pair for that line. Each line from the .csv is passed to this function below, and I attempt to store the (string, double) pairs as mentioned, but after executing, all the pairs have 0.0 as the double value. I am not sure if there is there is a problem in my try/catch or looping method through each token. Any hints are appreciated.
public void a(Text t) {
StringTokenizer word = new StringTokenizer(t.toString(), ", ");
int count = 0;
double val = 0.0;
String keep = new String("");
boolean loop = true;
while (loop) {
String nextWord = word.nextToken ();
if (count == 2) {
//string in pair
keep = nextWord;
//loop until at last column and store word
while (word.hasMoreTokens()){
nextWord = word.nextToken();
}
loop = false;
//check if string can be cast to double
try{
Double.parseDouble(nextWord);
} catch(NumberFormatException e) {
val = 0.0;
} catch(NullPointerException e) {
val = 0.0;
}
val = Double.parseDouble(nextWord);
}
count++;
}
// then not relevant code to store (keep, val) pair for rest of code
}
You should avoid StringTokenizer because it is a deprecated library. Using string.split(). Here is a much simpler solution
public void a(Text t) {
String[] line = t.toString().split(", ");
//check if string can be cast to double
try{
Double.parseDouble(line[3]);
} catch(NumberFormatException e) {
line[3] = "0.0";
}
}
If the column 4 can be casted to double, it will keep it as it is otherwise it will put it as "0.0". The caveat is that since java can only have one datatype in string, you can't store it as double, however, whenever you want to use this value, you can parse it on spot without worrying that it will throw an exception".
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
I'm currently working on a program that accepts integer values at one point (using Scanner method nextInt). Of course, if you type "one" instead of "1", the program crashes. I'm trying to get it instead to just to say that it was an invalid input and to try again if it isn't an integer, and continue if the value is an integer. So far I'm using the Scanner method hasNextInt, which determines if the value is an integer and returns a boolean value, but the part I'm having trouble with is continuing if an integer value was inputted. So is it possible to continue the program with the inputted value without having to ask for it again?
Since you are using java.util.Scanner, there is a method
scanner.hasNextInt();
That checks if there is an integer input.
int value = 0;
if(scanner.hasNextInt()) {
value = scanner.nextInt();
} else {
// handle bad input
}
You could try:
...
Scanner in = new Scanner(System.in);
try {
String intS = in.nextLine();
int intI = Integer.parseInt(intS);
} catch (Exception e) {
System.out.println("Error, no Int!")
//or something
}
...
if (x == (int)x)
{
// Number is integer
}
and try that too
Object x = someApi();
if (x instanceof Integer)
How can I check if a value is of type Integer?
and
How to check if the value is integer in java?
If there is a string variable containing a number string , is there any function to identify whether the value can be converted to int, or double, or anything else?? i need the function name in java
String sent3 = "123";
System.out.println(sent3.matches("[0-9]+"));
System.out.println(sent3.matches("[0-9]+\\.[0-9]+"));// for double
output :- true
If the output is true then it can be converted into int.
Follow this link for more regex
My solution involves trying to parse the string into the various types, and then looking for exceptions that Java might throw. This is probably an inefficient solution, but the code is relatively short.
public static Object convert(String tmp)
{
Object i;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
try {
i = Double.parseDouble(tmp);
} catch (Exception p) {
return tmp; // a number format exception was thrown when trying to parse as an integer and as a double, so it can only be a string
}
return i; // a number format exception was thrown when trying to parse an integer, but none was thrown when trying to parse as a double, so it is a double
}
return i; // no numberformatexception was thrown so it is an integer
}
You can then use this function with the following lines of code:
String tmp = "3"; // or "India" or "3.14"
Object tmp2 = convert(tmp);
System.out.println(tmp2.getClass().getName());
You can convert the function into inline code to test if it is an integer, for example:
String tmp = "3";
Object i = tmp;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
// do nothing
}
I was a little sloppy and tried to catch normal Exceptions, which is rather generic - I suggest you use "NumberFormatException" instead.
String test = "1234";
System.out.println(test.matches("-?\\d+"));
test = "-0.98";
System.out.println(test.matches("-?\\d+\\.\\d+"));
The first one matches (ie prints true) any integer (not int, integer) with an optional - sign in front. The second one matches any double value with an optional - sign, at least one digit before a required decimal point, and at least on digit following the decimal point.
Also, the function name is String.matches and it uses regular expressions.
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.