Math.min doesn't like numbers starting with 0. (0700) [duplicate] - java

This question already has answers here:
Why is 08 not a valid integer literal in Java?
(6 answers)
Closed 2 years ago.
I've been getting problems with the Math.min more so when I try to do
System.out.println(Math.min(0700,1400));
it returns 448 instead of 0700 the minimum value. I know it works when the 0 isn't there, but due to user input I kinda need it to be formatted that way. Is there any way around this, maybe like a substitute method or a quick efficient way to get rid of the 0 before I put it in Math.min parameter. I could do an if statement that checks then parses a substring, but that seems to tedious and inefficient. Any ideas?

Call the following function on any of the inputs with leading 0s (given that they are strings), then convert the new string into an integer with Integer.parseInt and then proceed with your normal Math.min function on this final integer:
//This function takes in a string that is of the form of a integer with
//leading zeros i.e. it would take in 0008000 and return the string 8000
public static String removeZeros(String str) {
String regexpattern = "^0+(?!$)"; //regex pattern to find leading zeros
str = str.replaceAll(regexpattern, ""); //remove leading zeros in string
return str; //return string
}

Related

how to get the numeric value (integer or float) of a string? [duplicate]

This question already has answers here:
Converting String to Number in Java
(9 answers)
Closed 1 year ago.
Hi everyone I am trying to get the numeric value inside a string. So far this method works well for me to obtain integers. But now I would also like to be able to obtain numbers that contain decimals.
if I want to extract the number that a String contains I use:
getNumbers("delay: 5 days")
output = 5
Now I want to get the number of "this a sample, delay: 7.1 days"
output = 7.1
Remark: the str always can change, but always will have a number (integer or float)
public String getNumbers(String str){
str = str.replaceAll("[^\\d]", " ");
str = str.trim();
str = str.replaceAll(" +", " ");
if (str.equals(""))
return "-1";
return str;
}
You can use regex for retrieving only digits from string, try this:
String numbers = Double.valueOf(yourStrValue.replaceAll("[^\\d.]+|\\.(?!\\d)", "")).toString()
but watch out for discrete numbers will be merged by this way. For example if u have 34fdf^.98 this process produced 34.98
Try using Double.parseDouble(str) in order to parse the double value. However, keep in mind that you will need to remove all the non-number characters from the string.

representing strings with certain integers [duplicate]

This question already has answers here:
Convert character to ASCII numeric value in java
(22 answers)
Closed 8 years ago.
I am trying to create a system that gets a string from the user and converts it to an integer. I want an integer representation for each letter, that way any string can be converted to an integer. I have tried putting each character of the string into an array, and then checking one by one for every letter. That method became to messy, so I was wondering if there was also a shorter way of doing this.
I want an integer representation for each letter
Use String to get Character Array by the use of "yourString".toCharArray();
Use ForEach loop to get int for every character.
for(char c:yourstring.trim().toCharArray())
{
int a=(int)c;
arrayList.add(a); //store integers to arrayList or array as you wish
}
Maybe the getNumericValue() method of Character is what you are after? You could use it in a loop.
If you want to convert a string to an integer you can try doing the following:
int c = Integer.parseInt("Your String");
For converting a letter to a string you can try the following:
String word = "abcd";
StringBuilder build = new StringBuilder();
for (char c : word.toCharArray()) {
build.append((char)(c - 'a' + 1));
}
So basically you subtract to find the integer value of the letter. NOTE: this only works for strings that are all in lower case. If you have letters in upper case you will have to convert them to lower case before applying the above.

(JAVA) how to use charAt() to find last digit number (or rightmost) of any real number?

Hello Im new to programming
and as title I was wonder how you can find last digit of any given number?
for example when entering in 5.51123123 it will display 3
All I know is I should use charAt
Should I use while loop?
thanks in advance
You would want to do something like this:
double number = 5.51123123;
String numString = number + "";
System.out.println(numString.charAt(numString.length()-1));
When you do the number + "", Java "coerces" the type of number from a double to a string and allows you to perform string functions on it.
The numString.length()-1 is because numString.length() returns the count of all the characters in the string BUT charAt() indexes into the string and its indexing begins at 0, so you need to do the -1 or you'll get a StringIndexOutOfBoundsException.
You can use below function simply and you can customize data types accordingly,
private int getLastDigit(double val){
String tmp = String.valueOf(val);
return Integer.parseInt(tmp.substring(tmp.length()-1));
}
You can't use charAt on a floating point variable (or any other data type other than Strings). (Unless you define a charAt method for your own classes...)
You can, however, convert that floating point number to a string and check the charAt(str.length()-1).
Convert your float variable to string and use charAt(strVar.length - 1).
double a=5.51123123;
String strVar=String.valueOf(a);
System.out.print(strVar.charAt(strVar.length -1);
Double doubleNo = 5.51123123;
String stringNo = doubleNo.toString();
System.out.println(stringNo.charAt(stringNo.length()-1));

Character Concatenation Resulting in Numerical Output [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 9 years ago.
In a programming language called Java, I have the following line of code:
char u = 'U';
System.out.print(u + 'X');
This statement results in an output like this:
173
Instead of
UX
Am I missing something? Why isn't it outputing 'UX'? Thank you.
Because you are performing an addition of chars. In Java, when you add chars, they are first converted to integers. In your case, the ASCII code of U is 85 and the code for X is 88.
And you print the sum, which is 173.
If you want to concatenate the chars, you can do, for example:
System.out.print("" + u + 'X');
Now the + is not a char addition any more, it becomes a String concatenation (because the first parameter "" is a String).
You could also create the String from its characters:
char[] characters = {u, 'X'};
System.out.print(new String(characters));
In this language known as Java, the result of adding two chars, shorts, or bytes is an int.
Thus, the integer value of U (85) is added to the integer value of X (88) and you get an integer value of 173 (85+88).
To Fix:
You'll probably want to make u a string. A string plus a char will be a string, as will a string plus a string.
String u = "U"; // u is a string
System.out.print(u + 'X'); // string plus a char is a string
String u = "U";
System.out.print(u + "X");
instead of char type use String class or StringBuilder class
Another way to convert one of the characters to a string:
char u = 'U';
System.out.print(Character.toString(u) + 'X');
This way could be useful when your variable is of type char for a good reason and you can't easily redeclare it as a String.
That "language called Java" bit amused me.
A quick search for "java concatenate" (which I recommend you do now and every time you have a question) revealed that most good Java programmers hate using + for concatenation. Even if it isn't used numerically when you want string concatenation, like in your code, it is also slow.
It seems that a much better way is to create a StringBuffer object and then call its append method for each string you want to be concatenated to it. See here: http://www.ibm.com/developerworks/websphere/library/bestpractices/string_concatenation.html

Java Split String Using Delimiter [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Matching a “.” in java
I have a String 1.2.4 which i want to split and get 2 to compare it with another String that i get.
I am trying to do the following
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
int oldVer = Integer.parseInt(old_ver.nextToken());
oldVer = Integer.parseInt(old_ver.nextToken());
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
int newVer = Integer.parseInt(new_ver.nextToken());
newVer = Integer.parseInt(new_ver.nextToken());
if (oldVer == newVer) {
return true;
}
IS there a better way to do it using .Split()
The problemis that in Regex "." is a single character. Hence, you need to escape it using "\\."
Similarly, you can use
string.split("\\.");
EDIT:
split() method of the String class uses Pattern and Matcher internally which is normally the API used for Regex in Java.
So there is no problem going with split.
In your code, 1.2.1 would be "compatible" with 3.2.0, and this looks like a serious problem, regardless if you use String.split or not. Also, you do not need to parse version numbers into integers as you only compare for equality.
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
return (old_ver.nextToken().equals(new_ver.nextToken() &&
old_ver.nextToken().equals(new_ver.nextToken() );
You can surely do with String.split as well:
String [] oldV = String.split(oldVersion,"\\.");
String [] newV = String.split(newVersion,"\\.");
return oldV[0].equals(newV[0]) && oldV[1].equals(newV[1]);
The String.split() version seems slightly shorter but but for me it looks slightly more difficult to read because:
It involves additional thinking step that dot (.) is a reserved char and must be escaped.
"Next element and then following element" seems involving less thinking effort than "element at position 0 and then element at position 1".
It may pay to have some version comparator that first compares major, then intermediate and then minor parts of the version number the way that we could have the tests like "1.2.4 or later".

Categories

Resources