Can I convert a String variable into a int variable [duplicate] - java

This question already has answers here:
Extract Integer Part in String
(9 answers)
Closed 7 years ago.
Is there a way to get a Integer variable from a String object, something like:
String string = "Render.SCREEN_WIDTH_TILES";
// SCREEN_WIDTH_TILES is a Render Integer value referenced in other class
I want the string variable to hold the reference to the specified int.
What I want from that string value is to "transform it" into a int value,
Is it possible to do this?
I can't find a way to handle an integer value as a variable in a string.

You seem to be misunderstanding how Integer.parseInt(s) works. The documentation clearly states:
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign - (\u002D) to indicate a negative value or an ASCII plus sign + (\u002B) to indicate a positive value.
The parameter to Integer.parseInt(s) must be a string that contains a number. Such as:
Integer.parseInt("12345")
Integer.parseInt("-45")
But not:
Integer.parseInt("Hello world")
Integer.parseInt("this will not work 4 you")
And certainly not: Integer.parseInt("Render.SCREEN_WIDTH_TILES - 1");

Related

Use of Integer.getInteger() [duplicate]

This question already has answers here:
Why does int num = Integer.getInteger("123") throw NullPointerException?
(3 answers)
Closed 7 years ago.
According to definition
The java.lang.Integer.getInteger(String nm) method determines the integer value of the system property with the specified name.
Can someone describe me the definition in simple terms.
Where is Integer.getInteger needed. Where can i use it. Why does the below program prints different outputs.
String str1 = "sun.arch.data.model";
System.out.println(Integer.getInteger(str1,5));
System.out.println(Integer.getInteger(str1));
String str2 = "com.samples.data.model";
System.out.println(Integer.getInteger(str2,5));
System.out.println(Integer.getInteger(str2));
Output:
32
32
5
null
The Integer.getInteger(String) method states the following:
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 using the grammar supported by decode and an Integer object representing this value is returned.
If there is no property with the specified name, if the specified name is empty or null, or if the property does not have the correct numeric format, then null is returned.
The other method, with two parameters, has a default value that is returned instead of null, if the parameter is not set or is an invalid integer.
Since sun.arch.data.model is a valid property with a numeric value, its value is returned both times (it is 32). com.samples.data.model is either non-existent or non-numeric and so the invalid handling logic is invoked instead, returning the default of 5 when specified, and null in the second call, where the default isn't specified.

charAt(int index) method in String class of java cannot take long input? [duplicate]

This question already has answers here:
Reading a file larger than 2GB into memory in Java
(4 answers)
Closed 7 years ago.
I have a very long String upto 10^15 characters. I need to see what character is at a particular index but charAt() method takes integer parameter. How can I find character at a particular index (>10^9) ?
Edit: I figured out I can't store String of order 10^15 but I am wondering is there a particular class in java for storing very large strings?
In the String class, the characters are stored in an array (private final char value[]), and Java arrays are indexed with an int.
This explains why the charAt() method takes an int as a parameter instead of a long, and why you won't be able to store any string with more than 2^31 characters anyway.

Assign property value with type conversion in Java

What is the best way to assign a value with type conversion to a property of an object in Java.
For eg: A Person class with age field as an integer. If the following statement has to assign integer 21 to age field, then what should be the implementation of set method? [Note: 21 is passed as string]
ObjectUtils.set(person, "age", "21");
One way is to get the type of the field and type cast explicitly. Is there any better approach or library utility available to achieve this?
Take a look at BeanUtils.setProperty():
Set the specified property value, performing type conversions as required to conform to the type of the destination property.
You can achieve this by using reflexion:
using this you can get the attribute type dynamically, something like this:
Person p = ...; // The object you want to inspect
Class<?> c = p.getClass();
Field f = c.getDeclaredField("age");
f.setAccessible(true);
String typeOfAge = (String) f.getType(p);
After you have the attribute type its easy to cast the value.
use Integer.parseInt(String) in your set method. Make sure you catch the exception for an invalid number. Here is hte javadoc for parseInt
parseInt
public static int parseInt(String s) throws NumberFormatException Parses the string
argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an
ASCII minus sign '-' ('\u002D') to indicate a negative value. The
resulting integer value is returned, exactly as if the argument and
the radix 10 were given as arguments to the parseInt(java.lang.String,
int) method. Parameters: s - a String containing the int
representation to be parsed Returns: the integer value represented by
the argument in decimal. Throws: NumberFormatException - if the string
does not contain a parsable integer.

set long values in a textfield [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert number to words in java
I am trying to set the long value in the textfield the modification of my code is as below error what it is showing is required long found int
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
long jml = Long.parseLong(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
The NumberFormatException is Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. So, the exception could be because the maximum value of a java int is 2,147,483,647 (which is a 10-digit integer).
The error is occuring in the below line, And looks like you are using Integer.parseInt() method in the below line,
at myproj.Certificates.jTextField2MouseClicked(Certificates.java:268)
When the value that is being passed to the method Integer.parseInt() is greater than Integer.MAX_VALUE (2,147,483,647), you will receive the java.lang.NumberFormatException.
And since 10000000000 is greater than 2,147,483,647 you are getting the NumberFormatException.

Prevent Int from changing 012345 to 5349 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Integer with leading zeroes
The program I am coding requires me to label an item with an inventory number of 012345 and store it in a int variable.
This is a stripped down example of what I am doing:
int test = 012345;
System.out.println(test);
this prints as:
5349
How do I get it to print out as 012345 rather than 5349?
EDIT: I am entering this into the parameter of a constructor for a custom class i am initializing. Then I use a method to return what the current number is, then print it to the terminal window.
You get a wrong number because when you prepend zero to an integer literal, Java interprets the number as an octal (i.e. base-8) constant. If you want to add a leading zero, use
int test = 12345;
System.out.println("0"+test);
You can also use the formated output functionality with the %06d specifier, like this:
System.out.format("%06d", num);
6 means "use six digits"; '0' means "pad with zeros if necessary".
As already said, int value with leading zero is considered as octal value. If you don't need to have test as int, why not make it string? Like
String test= new String("012345");
And if you want to use int for test, you can do not prepend 0, rather just use the number and prepend 0 at the time of printing.
In case if you're wondering how will you find how many leading zero are to be prepended, you may do like this
int lengthOfItemID=6;
int test=12345;
String test1=new String("000000"+test);
System.out.println(test1.substring(test1.length()-lengthOfItemID));
Pardon syntax mistakes, been years I last worked with java.
You can get the right result by using Integer.parseInt. That will make your string into a decimal string. (found here). The JAVA API here states that it takes a string and returns a signed decimal.

Categories