I was wondering how can I take some numbers in a string and convert them to an integer type? for example if a user entered 12:15pm how can I get 1 and 2 and make an int with value 12?
Given the example above, you could try something like this:
final int value = Integer.parseInt(input.substring(0, input.indexOf(':'))); //value = 12
Where input = 12:15pm in this case.
Generally speaking, just use a combination of String#indexOf(String), String#substring(int, int) and Integer.parseInt(String).
Read the String and Integer API's
You can use the String.split() to get the two numeric strings
You can use Integer.parseInt(...) to convert the String to an int.
Edit: Using the split() you can do something like:
String time = "12:34pm";
int hour = Integer.parseInt( time.split(":")[0] );
Related
The user can insert an random string that can only contains numbers.
But it must been possible to calculate it with an integer.
the problem is the user insert a string like 010 + integer(1) it would result in 11;
but i want to return a string 011
But the user can also enter numbers like 001, 0001, etc
What is the best approach here? I have try to use
String.format("%05d", yournumber); but i does not work with variable strings
I also came across
String str = "abcd1234";
String[] part = str.split("(?<=\\D)(?=\\d)");
System.out.println(part[0]);
System.out.println(part[1]);
If i use it like this i got a new problem.
how to split the number in a right way.
Any idea what i'm missing
Considering you are handling Integer number (not binary )
Try something like this:
String input ="001";//your user input
/**
* your check here if input is a number
*/
int len=input.length();
int inputInteger=Integer.parseInt(input);
inputInteger+=1;
String output=String.format("%0"+len+"d", inputInteger);
System.out.println(output);
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);
I have 4 strings:
str1 = 10110011;(length of all string is:32)
str2 = 00110000;
str3 = 01011000;
str4 = 11110000;
In my project I have to add these string and the result should be:
result[1] = str1[1]+str2[1]+str3[1]+str4[1];
result should be obtained as addition of integer numbers.
For the example above, result = 22341011
I know integer to string conversion in Java is very easy but I found string to integer conversion a little harder.
To parse Integers -2^31 < n < 2^31-1 use:
Integer value = Integer.valueOf("10110011");
For numbers that are larger, use the BigInteger class:
BigInteger value1 = new BigInteger("101100111011001110110011101100111011001110110011");
BigInteger value2 = // etc
BigInteger result = value1.add(value2).add(value3); //etc.
The simplest way to do this is with Integer.parseInt(str1). Returns an int containing the value represented by the string.
valueOf() returns an Integer object, rather than an int primitive.
Because your numbers are so big they will not fit in an int. Use the BigInteger class.
I am not known about your project and what actually your problem is. But I came to guess from your partial information that, you have multiple set of strings in bit representation as you explained.
str1 = "1000110.....11";
str1 = "1110110.....01"; etc
adding those decimal values,gives an ambiguous result as an integer can be the sum of multiple integer values. Just see an example below where there are total 5 possibilities[with positive decimal values] to yield 6.
1+5 = 6;
2+4 = 6;
3+3 = 6;
4+2 = 6;
5+1 = 6;
If you proceed in that way you just do an error,nothing else in your case.
One better solution can be,
compute the decimal values of individual strings. Instead of adding(+) them, just concat(join) them to form a single string.
I am suggesting this approach because, This gives always a unique value and later you may need to know individual strings decimal values.
String strVal1 = String.format(computeDecimal(str1));
String strVal2 = String.format(computeDecimal(str2));
String strVal3 = String.format(computeDecimal(str3));
.
.
.
String strValn = String.format(computeDecimal(strn));
String myVal = String.concate(strVal1,strVal1,strVal1,....strValn);
Now you can treat your string as your wish.
//This will give you a non conflicting result.
Better to implement above approach than BigIntegers.
Hope this helps you greatly.
I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}
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+"";