java convert from string to int - java

I need to parse the value of a label so that it can be stored as an Integer
JLabel lblSeatNo;
int seatNo;
seatNo = Integer.parseInt(lblSeatNo.getText());
It has worked other times I have used with method, however now I am getting a Number Format Exception and I don't understand why.
If it helps with value of the label can vary, it's general format is something like: "A131" or "B504"
Thankyou.

Assuming you want this as a hex number (that is base 16), you must supply the radix to your parseInt call -
seatNo = Integer.parseInt(lblSeatNo.getText(), 16);
if you want the decimal value (e.g. base 10) and to skip the letter, you could do
seatNo = Integer.parseInt(lblSeatNo.getText().substring(1));

Try int value = Integer.parseInt(hexString, 16); if you know that the string representation will always be hexadecimal. You might also want to check the documentation of the method in question.

Depends on what you are wanting:
If you want to just parse the numbers (not including a, b, etc) then you have to call substring to remove the letter.
if the letter is meant to be there as a hex number then you can call
Integer.parseInt(hexNo, 16)

follow this link
How to parse hex color String to Integer
eg. Integer.parseInt(myHexValue,16)

From your comments it seems like you want to extract just the number from the Seat label. But since you say that you also need to recreate the seat label then in your object you may also want to add a String for the row which will contain the Letter
So you could do something like this (assuming only ever a single letter)
int seatNo = Integer.parseInt(lblSeatNo.getText().substring(1));
String row = lblSeatNo.getText().subString(0,1);
Then to get the label again
String label = row + seatNo;

Related

Multiplying ascii code and getting string back

I am trying to convert a string to ascii code and then multiplying that concatenation of the ascii codes by a number.
For example
String message = "Hello";
String result = "";
ArrayList arrayList = new ArrayList();
int temp;
for(int i = 0; i < message.length(); i++){
temp = (int) message.charAt(i);
result = result + String.value(temp).toString();
arrayList.add(String.valueOf(temp).toString());
}
I have tried two different ways, but there is always a catch with each one.
If I just concatenate all the ascii codes together into a string and I get 72101108108111 as my new string, the problem now is how can I get the original string back from this? This is because it is not obvious where each one character code starts and ends and the next one begins.
Another way I tried doing this was to use an array. I would receive |72|101|108|108|111| in an array. Obviously the codes are split here, but if I wanted to multiply this whole array (all the numbers as one number) by a number and then how would I get the array back together?
These are two different ways I have thought to solve this, but I have no idea how to get the string back out of these if I multiply the ascii by a number.
You don't need to modify the original string nor the ascii code string. Just have them both there, then whenever you need to get the numerical value of the string, just use X.valueOf(...)** method. Example,
final String message = "Hello";
final String result = "72101108108111";
long value = Long.valueOf(result);
If you do not want to store the two strings, then you should go with the array method. To get a numerical value, you simply concatenate all the strings in the array into one and use the X.valueOf(..) method.
And to get back the original string, use Integer.valueOf(...) on each string in the array, then cast each one to char.
System.out.println((char)Integer.valueOf("111").intValue());
** Note by X.valueOf(..), X doesn't have to be Long or Integer as I have shown. As you mentioned the value can get really large so BigInteger should be prefered above others

Convert hexadecimal string to hexadecimal integer in java

I have hexadecimal String eg. "0x103E" , I want to convert it into integer.
Means String no = "0x103E";
to int hexNo = 0x103E;
I tried Integer.parseInt("0x103E",16); but it gives number format exception.
How do I achieve this ?
You just need to leave out the "0x" part (since it's not actually part of the number).
You also need to make sure that the number you are parsing actually fits into an integer which is 4 bytes long in Java, so it needs to be shorter than 8 digits as a hex number.
No need to remove the "0x" prefix; just use Integer.decode instead of Integer.parseInt:
int x = Integer.decode("0x103E");
System.out.printf("%X%n", x);

How to check if a string variable contains negative value or not in java

I need to put a constraint for negative values on string variable. For Eg :--
string zeroval = "0.0000"
String x = "";
if (x==null) || (x.equals(zeroval)) { // code which checks if string x has 0 or null value
x = "--" // replace it by --
}
similarly i want to add another piece of code which checks if String x contains any negative values (for eg : "-0.025") and replace it by --
The above String x should not contain null/zero/negative values
Please help
Note :- In order to add negative value check convert the string to float as i cannot use pattern matching technique for eg:- x.equals("-")
Is your input data always meant to contain valid numbers? If so, you could just use:
BigDecimal number = new BigDecimal(text);
if (number.compareTo(BigDecimal.ZERO) <= 0) {
text = "--";
}
This will validate that it really is a number as well as performing the check. Additionally:
It copes with other representations of 0, e.g. "0.00", "0", "+0"
It uses BigDecimal to avoid oddities in binary floating point representations (e.g. a very small positive value being seen as 0). Unlikely to be a problem, but fundamentally you've got decimal data, so you might as well parse it that way.
Convert it to Integer or double using wrapper class.
String number="12.3434"
if(Double.parseDouble(number)<0)
//do stuff here
You could check if the string starts with a "-":
if (x==null) || (x.equals(zeroval) || x.startsWith("-")) {
x = "--";
}
I can't help but feel you are doing something ill-advised by using Strings to represent numerical data.
You could use Double.parseDouble(String) or Float.parseFloat (String). These methods will help you get a double or a float, respectively.
After this, you can easily check if the value is negative.

How can I do this int to String transformation?

I want to transform an int to a String such that:
0 -> "a"
1 -> "b"
2 -> "c"
and so on...
How can I do this?
You can convert from the character literal:
int input = 0;
String output = new Character((char) (input + 'a')).toString();
Your question is a little unclear, but it sounds like you want to be able to convert integers 0-25 to their corresponding alphabetical characters. If that's the case, your best bet logically is probably to use an enum. Though I may not be fully seeing the purpose of what you're trying to do (which is likely).
You could also write a utility method which just has a big switch statement to convert them.
An alternate method, for some java library flavor:
int value;
String output = Integer.toString(value + 10, 36);
which uses a radix of 36 to locate the right letter.

Java Double to String conversion without formatting

I have the number 654987. Its an ID in a database. I want to convert it to a string.
The regular Double.ToString(value) makes it into scientific form, 6.54987E5. Something I dont want.
Other formatting functions Ive found checks the current locale and adds appropriate thousand separators and such. Since its an ID, I cant accept any formatting at all.
How to do it?
[Edit] To clarify: Im working on a special database that treats all numeric columns as doubles. Double is the only (numeric) type I can retrieve from the database.
Use a fixed NumberFormat (specifically a DecimalFormat):
double value = getValue();
String str = new DecimalFormat("#").format(value);
alternatively simply cast to int (or long if the range of values it too big):
String str = String.valueOf((long) value);
But then again: why do you have an integer value (i.e. a "whole" number) in a double variable in the first place?
Use Long:
long id = 654987;
String str = Long.toString(id);
If it's an integer id in the database, use an Integer instead. Then it will format as an integer.
How about String.valueOf((long)value);
What about:
Long.toString(value)
or
new String(value)
Also you can use
double value = getValue();
NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
String strVal = f.format(value);
If what you are storing is an ID (i.e. something used only to identify another entity, whose actual numeric value has no significance) then you shouldn't be using Double to store it. Precision will almost certainly screw you.
If your database doesn't allow integer values then you should stored IDs as strings. If necessary make the string the string representation of the integer you want to use. With appropriate use of leading zeros you can make the alphabetic order of the string the same as the numeric order of the ints.
That should get you round the issue.
What about Long.toString((long)value) ?
double d = 56789;
String s = d+"";

Categories