Java get integer value from string - java

I'd like to get the integer value from my string. Below is my example.
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
But I just want to get the score which is 10. How can I do this?
UPDATED:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
bfLog.createEntry( firstNumber );
I save this to sqlite database.

You can use one of the String regex replace methods to capture the first digits in a captured group:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
.*? consumes initial non-digits(non-greedy)
(\\d+) Get the one or more available digits in a group!
.* Everything else (greedy).

This depends on whether anything else can change in your string.
If it's always the same apart from the number, you can use
int score = Integer.parseInt(strScore.substring(14,16))
because the digits "10" are at index 14 and 15 of the string.
If other stuff changes in your string, you should use a regular expression :
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

You can try this:
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
String intIndex = strScore.valueOf(10);
String intIndex = 10 // Result

Related

How can I remove white spaces from an input?

This is the input: enter image description here
I want to get the last number but how? (1,2,6)
I tried this:
String line = scanner.nextLine();
String[] parts = line.split(" ");
int ProductCount =Integer.parseInt(parts[3].replaceAll(" ", ""));
If you want the last number you can do it like this.
.*? reluctantly grab the characters
(\\d+)$ - capture one or more digits at end of string.
$1 back reference to captured value (21 in this case)
and convert to an int.
String s = "kssk sk k22 s 21";
int v = Integer.parseInt(s.replaceAll(".*?(\\d+)$","$1"));
System.out.println(v);
prints
21
A somewhat better alternative might be to do the following if there is always a space before the last number.
get the last index of a white space
and starting with the next character, get the substring and convert to an integer.
int i = s.lastIndexOf(' '); // returns -1 if no space is found.
int v = Integer.parseInt(s.substring(i+1));

(JAVA) convert decimal to Binary coded decimal?

For example, I would like to convert the int value 12 into a String output of BCD: 00 12 (0x00 0x12).
If I have int value of 256, it will be 02 56 (which is 0x02 0x56),
or if I have a int value of 999, it will be 09 99 (0x09 0x99),
9999 would be 99 99 (0x99 0x99).
Right now, my only solution is to create a String array of size 4, and calculate how many characters are there by converting the int value into String. If there are 2 characters, I will add 2 x 0 into the array first before adding the 2 characters, and then make them back into a single String variable.
Basically,
int value = 12;
String output = Integer.toString(value);
// then count the number of characters in the String.
// 4 minus (whatever number of characters in the String, add zeros
// add the characters:
stringArray[0] = "0";
stringArray[1] = "0";
stringArray[2] = "1";
stringArray[3] = "2";
// then, concatenate them back
If there are 3 characters, I will add one 0 into the array first before adding 3 characters. I was wondering if there is any other way?
You can use String.format to append leading 0 and use substring to split in to two part.
int value = 12;
String output = String.format("%04d",value);
System.out.println(output.substring(0,2)+" "+output.substring(2,4));
String.format("%04d",value) will append 0s in the front if the length is less than 4.
If you do not want to use substring you can use String.split and String.join like below.
System.out.println(
String.join(
" ",
Arrays.asList(
output.split("(?<=\\G.{2})")
)
)
);
output.split("(?<=\\G.{2})") will split the string in 2 characters each.
Is that what you are asking for?
public static String formatTheString(String string, int length) {
return String.format("%"+length+"s", string).replace(' ', '0');
}
and pass the values like
formatTheString(Integer.toString(256),4);
I think what you are asking is not correct.
refer this for BCD.
and below code is sufficient for what you need
System.out.printf("%04d",n);
in above code n is your number.

Check pattern of string

I want to ask if i got one variable.
for example:
String i = "1+1+1"
how do i check the string contain digit alternate with symbol.
if you have idea how to use regex also can.
my rough idea like this:-
Pattern=[0-9\-];
if(i.matches(Pattern) {
system.out.println("true");
else
system.out.println("false);
tq.
still new here
You can use (for integers only))
^(\d+[+\/%-])*\d+$
Explanation:
^ start of the string
\d+[+\/%-] any integer followed by an operator in the character set
* any number of times
\d+ followed by an integer
$ end of the string
See Demo
If you want to do it in java then to very a character as an integer at index x use this
String s = abc.substring(x, x+1);
Scanner scan = new Scanner(s);
if (scan.hasNextInt())
{
.
}
where abc is the given string.
Check weather the first character is integer if so then start from first if not then check second (as it is alternate) then loop over the string verying if integers are present at alternate position.

Converting String to Int when every element is not of int (JAVA)

Suppose I have String s = "123 USA" , how can I obtain only the number i.e '123' that is in the String? By that I mean what is the most efficient way of doing it?
Split the String on the space character.
For each String in the resulting String[], use the method from this answer to determine whether it is a valid integer or not. If it is a valid integer, then output that integer. Otherwise, ignore it.
If you know where the numbers are in the the string, i would do something like this.
String[] split = s.split();
This will give you an array equivalent to
String[] split = ["123", "USA"];
The split function will default to splitting by spaces(I believe).
From there you can use
int num = Integer.parseInt(split[0]);
// num = 123;
to convert the fist index of the split array into an int.
s.replaceAll("\\D+", " ").trim()
\\D+ matches non-digits
trim() clears whitespace
Example:
String testString = " ##!#! (!#)!# 123 USA 312";
Output: 123 312
If there is more than one number, the next step may be to use String.split().
To convert a String to an integer: Integer.parseInt(string)

Java: string tokenizer and assign to 2 variables?

Let's say I have a time hh:mm (eg. 11:22) and I want to use a string tokenizer to split. However, after it's split I am able to get for example: 11 and next line 22. But how do I assign 11 to a variable name "hour" and another variable name "min"?
Also another question. How do I round up a number? Even if it's 2.1 I want it to round up to 3?
Have a look at Split a string using String.split()
Spmething like
String s[] = "11:22".split(":");;
String s1 = s[0];
String s2 = s[1];
And ceil for rounding up
Find ceiling value of a number using Math.ceil
Rounding a number up isn't too hard. First you need to determine whether it's a whole number or not, by comparing it cast as both an int and a double. If they don't match, the number is not whole, so you can add 1 to the int value to round it up.
// num is type double, but will work with floats too
if ((int)num != (double)num) {
int roundedNum = (int)num + 1;
}

Categories

Resources