Java parse int/long from binary literal string - java

Java wonderfully provides Long.decode to parse most int formats, but not binary:
Long.decode("11") => 11
Long.decode("011") => 9
Long.decode("0x11") => 17
Long.decode("0b11") => java.lang.NumberFormatException
Is there a method that will parse a string containing a binary literal for me?
P.S.
I understand if I wanted to extract the radix/value myself I could use the binary form of Long.parseLong, but ideally what I'm looking for would be a function that could parse "0b11" without any pre-processing.

There is no way in the standard Java API. However, I would take a look at Long.decode() code and adapt it:
public static Long decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Long result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
/// >>>> Add from here
else if (nm.startsWith("0b", index) || nm.startsWith("0B", index)) {
index += 2;
radix = 2;
}
/// <<<< to here
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Long.valueOf(nm.substring(index), radix);
result = negative ? Long.valueOf(-result.longValue()) : result;
} catch (NumberFormatException e) {
// If number is Long.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Long.valueOf(constant, radix);
}
return result;
}
That's as close as it can be to the original method (Ctrl+clicking core Java methods is a good experience).

Java doesn't seem to provide one; however, is this code really that cumbersome that you need a library:
public static Long parseBinaryLiteral (String s)
{
if (s == null)
throw new NumberFormatException("null");
// no need to check 0B
s = s.toLowerCase();
String p = "";
if (s.startsWith("0b"))
p = s.substring(2);
else if (s.startsWith("-0b"))
p = "-" + s.substring(3);
else if (s.startsWith("+0b"))
p = s.substring(3);
else
throw new NumberFormatException("For input string: \"" + s + "\"");
return Long.parseLong(p, 2);
}

Related

JAVA: Method can't find value from another method

So I'm making a Binary to Decimal converter and I'm supposed to catch the invalid character if the user inputs an illegal argument. I believe I have the correct method for catching any characters that aren't 0 or 1.
However, when I try to implement this method into my primary method parseBinary, it says that it "Cannot Find Symbol" for illegal(iChar).
I can't add any more parameters to parseBinary because the user is only supposed to enter one string of 0's and 1's. I'm curious if I made this method for nothing because of this restriction, but this is the only way I know of going about it. I'm a novice. Any/all help is very appreciated.
public static int parseBinary(String binary) throws NumberFormatException {
if (!isBinary(binary)) {
throw new NumberFormatException("Invalid Format for a Binary String - Illegal character: " + illegal(iChar));
}
int power = 0;
int decimal = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += Math.pow(2, power);
}
power++;
}
return decimal;
}
public static boolean isBinary(String binary) {
for (char ch : binary.toCharArray()) {
if (ch != '1' && ch != '0'){
return false;
}
}
return true;
}
public static char illegal(String iChar)
{
char test = 0;
char arr[] = iChar.toCharArray();
for(char cha : arr)
{
if (cha != '1' && cha != '0')
{
test = cha;
}
}
return test;
}
As #mureinik said
instead of doing
throw new NumberFormatException("Invalid Format for a Binary String - Illegal character: " + illegal(iChar));
you must pass binary to the method illegal
change it to
throw new NumberFormatException("Invalid Format for a Binary String - Illegal character: " + illegal(binary));

String Math Algorithm Gone Wrong JavaFX

As I was building my first JavaFX project, I noticed that the calculator engine that I had built was a little off. With that being said, I went over my code for about an hour now, trying to figure out what is wrong and I couldn't find anything that connects to this strange bug in my program.
The calculator engine:
public static String BasicEval(String str, String function) {
int indexOfOperation = str.indexOf(function);
int downBoundary = indexOfOperation - 1;
int upBoundary = indexOfOperation + 1;
int closestUp = str.length(), closestDown = 0;
for (int index = 0; index < str.length(); index++) { // Searching for the closest white space (between vals.) to determine what are the two vals.
if (Math.abs(indexOfOperation - index) == 1) {
continue;
} else if ((str.charAt(index) == ' ') && ((indexOfOperation - index) > closestDown)) {
closestDown = index; //Finds the closest blank space in order to differentiate between elements.
} else if ((str.charAt(index) == ' ') && (Math.abs(indexOfOperation + index) < closestUp)) {
closestUp = index; //Finds the closest black space in order to differentiate between elements.
}
}
while (str.substring(upBoundary,closestUp).contains("X") || (str.substring(upBoundary,closestUp).contains("-") || (str.substring(upBoundary,closestUp).contains("+") || (str.substring(upBoundary,closestUp).contains("/") || (str.substring(upBoundary,closestUp).contains("^")))))) {
closestUp--;
}
double firstValue = Double.valueOf(str.substring((closestDown + 1), downBoundary));
double secondValue = Double.valueOf(str.substring(upBoundary + 1, (closestUp-1)));
double OperationResult;
switch (function) {
case "^" : OperationResult = Math.pow(firstValue,secondValue); break;
case "X" : OperationResult = (firstValue * secondValue); break;
case "/" : OperationResult = (firstValue / secondValue); break;
case "+" : OperationResult = (firstValue + secondValue); break;
case "-" : OperationResult = firstValue - secondValue; break;
default: OperationResult = -999.12349876; //ERROR
}
str = strSort(str,firstValue,secondValue,OperationResult);
return str;
}
A little bit about the engine: the engine itself supposes to evaluate math expressions inside strings, so for example an input would be: " 3 + 4 " and the answer would be: 7.0 as a double. The way I hoped to achive this was by deviding the str into 4 smaller sections by the spaces between the terms and operation sign. The problem is: the math gets all wierd as you use bigger numbers. The number -999.123... stands for an error in my program.
The engine works just fine for simple calculations that use low numbers, but as you start to use bigger numbers things get messy. Sometimes it also produces errors like: "empty string", which I don't understand why ..
For more info about the project or the engine please comment.
-- Keep in mind that I'm looking for an answer that would apply to my algorithm, not to javaFX in general-- (though I'd love to learn new stuff)
Thanks !!
Examples of how things aren't as they should be:
enter image description here
enter image description here
I'll post more pictures in the comments.
strSort Method
public static String strSort(String str, double firstValue, double secondValue, double result) {
//Method that sorts between which vals are ints and which ones are doubles. --> returns them in their current form.
int firstValueIndex = 0;
int secondValueIndex = 0;
if (!intOrDoubleTest(firstValue) && firstValue == secondValue){ // Special category : indexOf doesn't work since the two vals. are the same --> giving off the same index.
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Double.toString(secondValue),firstValueIndex+1);
} else if (intOrDoubleTest(firstValue) && firstValue == secondValue) { // Special category : indexOf doesn't work since the two vals. are the same --> giving off the same index.
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)),firstValueIndex+1);
} else if (intOrDoubleTest(firstValue) && intOrDoubleTest(secondValue)) { // First, sorts out the two vals.
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)));
} else if (!intOrDoubleTest(firstValue) && intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)));
} else if (intOrDoubleTest(firstValue) && !intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Double.toString(secondValue));
} else if (!intOrDoubleTest(firstValue) && !intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Double.toString(secondValue));
}
String strToReplace = str.substring(firstValueIndex, secondValueIndex); // Computing the range that need to be replaced.
if (intOrDoubleTest(result)) {
int intResult = intValue(result);
str = str.replace(strToReplace,Integer.toString(intResult));
} else if (!intOrDoubleTest(result)) {
str = str.replace(strToReplace,Double.toString(result));
}
return str;
}
public static boolean intOrDoubleTest(double value) {
return (value % 1 == 0); // True = val is Int, False = val is Double.
}
Found the problem:
The problem was in the strToReplace.substring the strSort method. So naturally, I re-wrote the entire method in a much simpler, nicer way.
public static String strSort(String str, double firstValue, double secondValue, double result) {
//Method that sorts between which vals are ints and which ones are doubles. --> returns them in their current form.
int firstValueIndex;
int secondValueIndex;
if (intOrDoubleTest(firstValue)) {
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
} else {
firstValueIndex = str.indexOf(Double.toString(firstValue));
}
if (intOrDoubleTest(secondValue)) {
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)), firstValueIndex+1);
} else {
secondValueIndex = str.indexOf(Double.toString(secondValue), firstValueIndex+1);
}
int lengthOfSecondVal;
lengthOfSecondVal = (int)(Math.log10(secondValue)+1);
String strToReplace = str.substring(firstValueIndex, secondValueIndex+lengthOfSecondVal); // Computing the range that need to be replaced.
if (intOrDoubleTest(result)) {
int intResult = intValue(result);
str = str.replace(strToReplace,Integer.toString(intResult));
} else if (!intOrDoubleTest(result)) {
str = str.replace(strToReplace,Double.toString(result));
}
return str;
}
public static boolean intOrDoubleTest(double value) {
return (value % 1 == 0); // True = val is Int, False = val is Double.
}
Thank you to all of you that helped !!

Java: Find the longest substring without any number and at least one upper case character

Came across a programming exercise and was stuck. The problem is:
You need to define a valid password for an email but the only
restrictions are:
The password must contain one uppercase character
The password should not have numeric digit
Now, given a String, find the length of the longest substring which
is a valid password. For e.g Input Str = "a0Ba" , the output should
be 2 as "Ba" is the valid substring.
I used the concept of longest substring without repeating characters which I already did before but was unable to modify it to find the solution to above problem. My code for longest substring without repeating characters is:
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
How about
final String input = "a0Ba";
final int answer = Arrays.stream(input.split("[0-9]+"))
.filter(s -> s.matches("(.+)?[A-Z](.+)?"))
.sorted((s1, s2) -> s2.length() - s1.length())
.findFirst()
.orElse("")
.length();
out.println(answer);
Arrays.stream(input.split("[0-9]+")) splits the original string into an array of strings. The separator is any sequence of numbers (numbers aren't allowed so they serve as separators). Then, a stream is created so I can apply functional operations and transformations.
.filter(s -> s.matches("(.+)?[A-Z](.+)?")) keeps into the stream only strings that have at least one upper-case letter.
.sorted((s1, s2) -> s2.length() - s1.length()) sorts the stream by length (desc).
.findFirst() tries to get the first string of the stream.
.orElse("") returns an empty string if no string was found.
.length(); gets the length of the string.
I suggest that you split your String to have an array of strings without digit:
yourString.split("[0-9]")
Then iterate over this array (says array a) to get the longest string that contains one Upper case character:
a[i].matches("[a-z]*[A-Z]{1}[a-z]*");
You can use a simple array. The algorithm to use would be a dynamic sliding window. Here is an example of a static sliding window: What is a Sliding Window
The algorithm should be as follows:
Keep track of 2 indexes of the array of char. These 2 indexes will be referred to as front and back here, representing the front and back of the array.
Have an int (I'll name it up here) to keep track of the number of upper case char.
Set all to 0.
Use a while loop that terminates if front > N where N is the number of char given.
If the next char is not a number, add 1 to front. Then check if that char is upper case. If so, add 1 to up.
If up is at least 1, update the maximum length if necessary.
If the next char is a number, continue checking the following char if they are also numbers. Set front to the first index where the char is not a number and back to front-1.
Output the maximum length.
You can use my solution which runs in O(n) time and finds the longest part without any digit and with a capital letter:
String testString = "skjssldfkjsakdfjlskdssfkjslakdfiop7adfaijsldifjasdjfil8klsasdfŞdijpfjapodifjpoaidjfpoaidjpfi9a";
int startIndex = 0;
int longestStartIndex = 0;
int endIndex = 0;
int index = 0;
int longestLength = Integer.MIN_VALUE;
boolean foundUpperCase = false;
while(index <= testString.length()) {
if (index == testString.length() || Character.isDigit(testString.charAt(index))) {
if (foundUpperCase && index > startIndex && index - startIndex > longestLength) {
longestLength = index - startIndex;
endIndex = index;
longestStartIndex = startIndex;
}
startIndex = index + 1;
foundUpperCase = false;
} else if (Character.isUpperCase(testString.charAt(index))) {
foundUpperCase = true;
}
index++;
}
System.out.println(testString.substring(longestStartIndex, endIndex));
You don't need regular expressions. Just use a few integers to act as index pointers into the string:
int i = 0;
int longestStart = 0;
int longestEnd = 0;
while (i < s.length()) {
// Skip past all the digits.
while (i < s.length() && Character.isDigit(s.charAt(i))) {
++i;
}
// i now points to the start of a substring
// or one past the end of the string.
int start = i;
// Keep a flag to record if there is an uppercase character.
boolean hasUppercase = false;
// Increment i until you hit another digit or the end of the string.
while (i < s.length() && !Character.isDigit(s.charAt(i))) {
hasUppercase |= Character.isUpperCase(s.charAt(i));
++i;
}
// Check if this is longer than the longest so far.
if (hasUppercase && i - start > longestEnd - longestStart) {
longestEnd = i;
longestStart = start;
}
}
String longest = s.substring(longestStart, longestEnd);
Ideone demo
Whilst more verbose than regular expressions, this has the advantage of not creating any unnecessary objects: the only object created is the longest string, right at the end.
I am using modification of Kadane algorithm to search the required password length. You may use isNumeric() and isCaps() function or include inline if statements. I have shown below with functions.
public boolean isNumeric(char x){
return (x>='0'&&x<='9');
}
public boolean isCaps(char x){
return (x>='A'&&x<='Z');
}
public int maxValidPassLen(String a)
{
int max_so_far = 0, max_ending_here = 0;
boolean cFlag = false;
int max_len = 0;
for (int i = 0; i < a.length(); i++)
{
max_ending_here = max_ending_here + 1;
if (isCaps(a.charAt(i))){
cFlag = true;
}
if (isNumeric(a.charAt(i))){
max_ending_here = 0;
cFlag = false;
}
else if (max_so_far<max_ending_here){
max_so_far = max_ending_here;
}
if(cFlag&&max_len<max_so_far){
max_len = max_so_far;
}
}
return max_len;
}
Hope this helps.
There are plenty of good answers here but thought it might be of interest to add one that uses Java 8 streams:
IntStream.range(0, s.length()).boxed()
.flatMap(b -> IntStream.range(b + 1, s.length())
.mapToObj(e -> s.substring(b, e)))
.filter(t -> t.codePoints().noneMatch(Character::isDigit))
.filter(t -> t.codePoints().filter(Character::isUpperCase).count() == 1)
.mapToInt(String::length).max();
If you wanted the string (rather than just the length), then the last line can be replaced with:
.max(Comparator.comparingInt(String::length));
Which returns an Optional<String>.
I'd use Streams and Optionals:
public static String getBestPassword(String password) throws Exception {
if (password == null) {
throw new Exception("Invalid password");
}
Optional<String> bestPassword = Stream.of(password.split("[0-9]"))
.filter(TypeErasure::containsCapital)
.sorted((o1, o2) -> o1.length() > o2.length() ? 1 : 0)
.findFirst();
if (bestPassword.isPresent()) {
return bestPassword.get();
} else {
throw new Exception("No valid password");
}
}
/**
* Returns true if word contains capital
*/
private static boolean containsCapital(String word) {
return word.chars().anyMatch(Character::isUpperCase);
}
Be sure to write some unit tests
public String pass(String str){
int length = 0;
boolean uppercase = false;
String s= "";
String d= "";
for(int i=0;i<str.length();i++){
if(Character.isUpperCase(str.charAt(i)) == true){
uppercase = true;
s = s+str.charAt(i);
}else if(Character.isDigit(str.charAt(i)) == true ){
if(uppercase == true && s.length()>length){
d = s;
s = "";
length = s.length();
uppercase = false;
}
}else if(i==str.length()-1&&Character.isDigit(str.charAt(i))==false){
s = s + str.charAt(i);
if(uppercase == true && s.length()>length){
d = s;
s = "";
length = s.length();
uppercase = false;
}
}else{
s = s+str.charAt(i);
}
}
return d;}
Here is a simple solution with Scala
def solution(str: String): Int = {
val strNoDigit = str.replaceAll("[0-9]", "-")
strAlphas = strNoDigit.split("-")
Try(strAlphas.filter(_.trim.find(_.isUpper).isDefined).maxBy(_.size))
.toOption
.map(_.length)
.getOrElse(-1)
}
Another solution using tail recursion in Scala
def solution2(str: String): Int = {
val subSt = new ListBuffer[Char]
def checker(str: String): Unit = {
if (str.nonEmpty) {
val s = str.head
if (!s.isDigit) {
subSt += s
} else {
subSt += '-'
}
checker(str.tail)
}
}
checker(str)
if (subSt.nonEmpty) {
val noDigitStr = subSt.mkString.split("-")
Try(noDigitStr.filter(s => s.nonEmpty && s.find(_.isUpper).isDefined).maxBy(_.size))
.toOption
.map(_.length)
.getOrElse(-1)
} else {
-1
}
}
This is a dynamic programming problem. You can solve this yourself using a matrix. It is easy enough. Just give it a try. Take the characters of the password as the rows and columns of the matrix. Add the diagonals if the current character appended to the last character forms a valid password. Start with the smallest valid password as the initial condition.
String[] s = testString.split("[0-9]");
int length = 0;
int index = -1;
for(int i=0; i< s.length; i++){
if(s[i].matches("[a-z]*.*[A-Z].*[a-z]*")){
if(length <= s[i].length()){
length = s[i].length();
index = i;
}
}
}
if(index >= 0){
System.out.println(s[index]);
}
//easiest way to do it:
String str = "a0Ba12hgKil8oPlk";
String[] str1 = str.split("[0-9]+");
List<Integer> in = new ArrayList<Integer>();
for (int i = 0; i < str1.length; i++) {
if (str1[i].matches("(.+)?[A-Z](.+)?")) {
in.add(str1[i].length());
} else {
System.out.println(-1);
}
}
Collections.sort(in);
System.out.println("string : " + in.get(in.size() - 1));
This is my solution with c#. I tested a range of strings and it gave me the correct value. Used Split. No Regex or Substrings. Let me know if it works; open to improvements and corrections.
public static int validPassword(string str)
{
List<int> strLength = new List<int>();
if (!(str.All(Char.IsDigit)))
{
//string str = "a0Bb";
string[] splitStrs = str.Split(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
//check if each string contains a upper case
foreach (string s in splitStrs)
{
//Console.WriteLine(s);
if (s.Any(char.IsUpper) && s.Any(char.IsLower) || s.Any(char.IsUpper))
{
strLength.Add(s.Length);
}
}
if (strLength.Count == 0)
{
return -1;
}
foreach (int i in strLength)
{
//Console.WriteLine(i);
}
return strLength.Max();
}
else
{
return -1;
}
}
I think this solution takes care of all the possible corner cases. It passed all the test cases in an Online Judge. It is a dynamic sliding window O(n) solution.
public class LongestString {
public static void main(String[] args) {
// String testString = "AabcdDefghIjKL0";
String testString = "a0bb";
int startIndex = 0, endIndex = 0;
int previousUpperCaseIndex = -1;
int maxLen = 0;
for (; endIndex < testString.length(); endIndex++) {
if (Character.isUpperCase(testString.charAt(endIndex))) {
if (previousUpperCaseIndex > -1) {
maxLen = Math.max(maxLen, endIndex - startIndex);
startIndex = previousUpperCaseIndex + 1;
}
previousUpperCaseIndex = endIndex;
} else if (Character.isDigit(testString.charAt(endIndex))) {
if (previousUpperCaseIndex > -1) {
maxLen = Math.max(maxLen, endIndex - startIndex);
}
startIndex = endIndex + 1;
previousUpperCaseIndex = -1;
}
}
if (previousUpperCaseIndex > -1)
maxLen = Math.max(maxLen, endIndex - startIndex);
System.out.println(maxLen);
}}
function ValidatePassword(password){
var doesContainNumber = false;
var hasUpperCase = false;
for(var i=0;i<password.length;i++){
if(!isNaN(password[i]))
doesContainNumber = true;
if(password[i] == password[i].toUpperCase())
hasUpperCase = true;
}
if(!doesContainNumber && hasUpperCase)
return true;
else
return false;
}
function GetLongestPassword(inputString){
var longestPassword = "";
for(var i=0;i<inputString.length-1;i++)
{
for (var j=i+1;j<inputString.length;j++)
{
var substring = inputString.substring(i,j+1);
var isValid = ValidatePassword(substring);
if(isValid){
if(substring.length > longestPassword.length)
{
longestPassword = substring;
}
}
}
}
if(longestPassword == "")
{
return "No Valid Password found";
}
else
{
return longestPassword;
}
}

how can I check if a string is a floating point number?

In my program I'm going to store user input in an array then going to check each character to see if it's a digit or dot or E or negative sign after that I'll store it in to an array called temps.
Now I have problem in my fleating method () that don't how should I make my condition for the pattern of floating number digit-digit-dot-digit-digit (e.g 12.22)
I have my work here:
public void sorting(String data) {
String[] temps = new String[200];
int cpos = 0;
int tpos = 0;
Arrays.fill(temps, null);
if (str.isEmpty() == false) {
char char1 = str.charAt(cpos);
int i = 0;
while (i < str.length()) {
char1 = str.charAt(cpos);
char1 = str.charAt(tpos);
System.out.println("the current value is " + char1 + " ");
tpos++;
if (Character.isDigit(char1)) {
temps[cpos] = "Digit";
// System.out.println(" this number is digit");
cpos++;
} else if (char1 == 'e' || char1 == 'E') {
temps[cpos] = "s_notaion";
cpos++;
} else if (char1 == '-') {
temps[cpos] = "negative";
cpos++;
} else if (char1 == '.') {
temps[cpos] = ".";
cpos++;
}
i++;
}
}
}
here is the method for floating number
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (data[i]== "Digit" )
&& data[i]=="." && data[i]"Digit"){
// here is the problem for the condition
}
}
return false;
}
If I understood correctly, the Data array has stuff like ["Digit","Digit",".","Digit"]
So you want the
private static boolean floating(String [] data) {
method to return true if the array only has "Digit" entries and exactly one "." entry? is that it?
If so:
boolean foundLeDigit = false;
for (int i = 0; i < data.length; i++) {
if (data[i].equals("Digit") == false && data[i].equals(".") == false {
//we found something other than a Digit or . it's not a float
return false;
}
if(data[i].equals(".")) {
if(foundLeDigit) { return false; //as we found 2 "." }
foundLeDigit = true
}
}
return foundLeDigit;
The easiest way to test if a String can represent a float is to try to parse it:
String testString = "1.2345";
double result;
try {
result = Double.parseDouble(testString);
System.out.println("Success!")
}
catch (NumberFormatException nfe) {
// wasn't a double, deal with the failure in whatever way you like
}
The questions lacks a bit of context, so for my answer I'm going to presume that this is homework requiring a manual solution, and that all floating point numbers are supposed to be accepted.
Your approach (while over-engineered) is half-right: you are reducing the input string into classes of characters - digit, sign, exponent marker. What is missing is that now you have to make sure that these character classes come in the right order.
Identify the various parts of float numbers (just look at 0, -1.0, 400E30, 42.1E-30) and you'll see that they come in a specific order, even if some are optional, and that each part imposes restrictions on what characters are allowed there. For example, if there is an 'E' in the number, it has to be followed by a number (with optional sign).
So as you step through the characters of the string, think about how you could keep track of where you are in the number, and base your character validation on that (this is the state machine #JonKiparsky was mentioning).
A few small things:
Don't compare strings with '==' - use equalsTo().
Think about what it means if sorting() finds a character which is neither a digit, a sign, or the exponent 'E'?
You allocate the temps array for 200 entries, but the input string could be larger.
using the regular expression is the best way to Handel this problem
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (str.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
System.out.println(" it's a floating number ");
correct= true;
break;
}else
correct = false;
}if (correct ==true){
return true;
}else
return false;
}

What's the best way to check if a String represents an integer in Java?

I normally use the following idiom to check if a String can be converted to an integer.
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
Is it just me, or does this seem a bit hackish? What's a better way?
See my answer (with benchmarks, based on the earlier answer by CodingWithSpike) to see why I've reversed my position and accepted Jonas Klemming's answer to this problem. I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.
If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using Integer.parseInt().
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
You have it, but you should only catch NumberFormatException.
Did a quick benchmark. Exceptions aren't actually that expensivve, unless you start popping back multiple methods and the JVM has to do a lot of work to get the execution stack in place. When staying in the same method, they aren't bad performers.
public void RunTests()
{
String str = "1234567890";
long startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(str);
long endTime = System.currentTimeMillis();
System.out.print("ByException: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(str);
endTime = System.currentTimeMillis();
System.out.print("ByRegex: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(str);
endTime = System.currentTimeMillis();
System.out.print("ByJonas: ");
System.out.println(endTime - startTime);
}
private boolean IsInt_ByException(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException nfe)
{
return false;
}
}
private boolean IsInt_ByRegex(String str)
{
return str.matches("^-?\\d+$");
}
public boolean IsInt_ByJonas(String str)
{
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
Output:
ByException: 31
ByRegex: 453 (note: re-compiling the pattern every time)
ByJonas: 16
I do agree that Jonas K's solution is the most robust too. Looks like he wins :)
org.apache.commons.lang.StringUtils.isNumeric
though Java's standard lib really misses such utility functions
I think that Apache Commons is a "must have" for every Java programmer
too bad it isn't ported to Java5 yet
Since there's possibility that people still visit here and will be biased against Regex after the benchmarks... So i'm gonna give an updated version of the benchmark, with a compiled version of the Regex. Which opposed to the previous benchmarks, this one shows Regex solution actually has consistently good performance.
Copied from Bill the Lizard and updated with compiled version:
private final Pattern pattern = Pattern.compile("^-?\\d+$");
public void runTests() {
String big_int = "1234567890";
String non_int = "1234XY7890";
long startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(big_int);
long endTime = System.currentTimeMillis();
System.out.print("ByException - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByException - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByRegex - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByRegex - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
IsInt_ByCompiledRegex(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByCompiledRegex - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
IsInt_ByCompiledRegex(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByCompiledRegex - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByJonas - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByJonas - non-integer data: ");
System.out.println(endTime - startTime);
}
private boolean IsInt_ByException(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException nfe)
{
return false;
}
}
private boolean IsInt_ByRegex(String str)
{
return str.matches("^-?\\d+$");
}
private boolean IsInt_ByCompiledRegex(String str) {
return pattern.matcher(str).find();
}
public boolean IsInt_ByJonas(String str)
{
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
Results:
ByException - integer data: 45
ByException - non-integer data: 465
ByRegex - integer data: 272
ByRegex - non-integer data: 131
ByCompiledRegex - integer data: 45
ByCompiledRegex - non-integer data: 26
ByJonas - integer data: 8
ByJonas - non-integer data: 2
It partly depend on what you mean by "can be converted to an integer".
If you mean "can be converted into an int in Java" then the answer from Jonas is a good start, but doesn't quite finish the job. It would pass 999999999999999999999999999999 for example. I would add the normal try/catch call from your own question at the end of the method.
The character-by-character checks will efficiently reject "not an integer at all" cases, leaving "it's an integer but Java can't handle it" cases to be caught by the slower exception route. You could do this bit by hand too, but it would be a lot more complicated.
Just one comment about regexp. Every example provided here is wrong!. If you want to use regexp don't forget that compiling the pattern take a lot of time. This:
str.matches("^-?\\d+$")
and also this:
Pattern.matches("-?\\d+", input);
causes compile of pattern in every method call. To used it correctly follow:
import java.util.regex.Pattern;
/**
* #author Rastislav Komara
*/
public class NaturalNumberChecker {
public static final Pattern PATTERN = Pattern.compile("^\\d+$");
boolean isNaturalNumber(CharSequence input) {
return input != null && PATTERN.matcher(input).matches();
}
}
There is guava version:
import com.google.common.primitives.Ints;
Integer intValue = Ints.tryParse(stringValue);
It will return null instead of throwing an exception if it fails to parse string.
I copied the code from rally25rs answer and added some tests for non-integer data. The results are undeniably in favor of the method posted by Jonas Klemming. The results for the Exception method that I originally posted are pretty good when you have integer data, but they're the worst when you don't, while the results for the RegEx solution (that I'll bet a lot of people use) were consistently bad. See Felipe's answer for a compiled regex example, which is much faster.
public void runTests()
{
String big_int = "1234567890";
String non_int = "1234XY7890";
long startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(big_int);
long endTime = System.currentTimeMillis();
System.out.print("ByException - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByException - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByRegex - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByRegex - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByJonas - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByJonas - non-integer data: ");
System.out.println(endTime - startTime);
}
private boolean IsInt_ByException(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException nfe)
{
return false;
}
}
private boolean IsInt_ByRegex(String str)
{
return str.matches("^-?\\d+$");
}
public boolean IsInt_ByJonas(String str)
{
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
Results:
ByException - integer data: 47
ByException - non-integer data: 547
ByRegex - integer data: 390
ByRegex - non-integer data: 313
ByJonas - integer data: 0
ByJonas - non-integer data: 16
This is shorter, but shorter isn't necessarily better (and it won't catch integer values which are out of range, as pointed out in danatel's comment):
input.matches("^-?\\d+$");
Personally, since the implementation is squirrelled away in a helper method and correctness trumps length, I would just go with something like what you have (minus catching the base Exception class rather than NumberFormatException).
You can use the matches method of the string class. The [0-9] represents all the values it can be, the + means it must be at least one character long, and the * means it can be zero or more characters long.
boolean isNumeric = yourString.matches("[0-9]+"); // 1 or more characters long, numbers only
boolean isNumeric = yourString.matches("[0-9]*"); // 0 or more characters long, numbers only
How about:
return Pattern.matches("-?\\d+", input);
This is a Java 8 variation of Jonas Klemming answer:
public static boolean isInteger(String str) {
return str != null && str.length() > 0 &&
IntStream.range(0, str.length()).allMatch(i -> i == 0 && (str.charAt(i) == '-' || str.charAt(i) == '+')
|| Character.isDigit(str.charAt(i)));
}
Test code:
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
Arrays.asList("1231231", "-1232312312", "+12313123131", "qwqe123123211", "2", "0000000001111", "", "123-", "++123",
"123-23", null, "+-123").forEach(s -> {
System.out.printf("%15s %s%n", s, isInteger(s));
});
}
Results of the test code:
1231231 true
-1232312312 true
+12313123131 true
qwqe123123211 false
2 true
0000000001111 true
false
123- false
++123 false
123-23 false
null false
+-123 false
You just check NumberFormatException:-
String value="123";
try
{
int s=Integer.parseInt(any_int_val);
// do something when integer values comes
}
catch(NumberFormatException nfe)
{
// do something when string values comes
}
If your String array contains pure Integers and Strings, code below should work. You only have to look at first character.
e.g. ["4","44","abc","77","bond"]
if (Character.isDigit(string.charAt(0))) {
//Do something with int
}
You can also use the Scanner class, and use hasNextInt() - and this allows you to test for other types, too, like floats, etc.
Another option:
private boolean isNumber(String s) {
boolean isNumber = true;
for (char c : s.toCharArray()) {
isNumber = isNumber && Character.isDigit(c);
}
return isNumber;
}
If you want to check if the string represents an integer that fits in an int type, I did a little modification to the jonas' answer, so that strings that represent integers bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE, will now return false. For example: "3147483647" will return false because 3147483647 is bigger than 2147483647, and likewise, "-2147483649" will also return false because -2147483649 is smaller than -2147483648.
public static boolean isInt(String s) {
if(s == null) {
return false;
}
s = s.trim(); //Don't get tricked by whitespaces.
int len = s.length();
if(len == 0) {
return false;
}
//The bottom limit of an int is -2147483648 which is 11 chars long.
//[note that the upper limit (2147483647) is only 10 chars long]
//Thus any string with more than 11 chars, even if represents a valid integer,
//it won't fit in an int.
if(len > 11) {
return false;
}
char c = s.charAt(0);
int i = 0;
//I don't mind the plus sign, so "+13" will return true.
if(c == '-' || c == '+') {
//A single "+" or "-" is not a valid integer.
if(len == 1) {
return false;
}
i = 1;
}
//Check if all chars are digits
for(; i < len; i++) {
c = s.charAt(i);
if(c < '0' || c > '9') {
return false;
}
}
//If we reached this point then we know for sure that the string has at
//most 11 chars and that they're all digits (the first one might be a '+'
// or '-' thought).
//Now we just need to check, for 10 and 11 chars long strings, if the numbers
//represented by the them don't surpass the limits.
c = s.charAt(0);
char l;
String limit;
if(len == 10 && c != '-' && c != '+') {
limit = "2147483647";
//Now we are going to compare each char of the string with the char in
//the limit string that has the same index, so if the string is "ABC" and
//the limit string is "DEF" then we are gonna compare A to D, B to E and so on.
//c is the current string's char and l is the corresponding limit's char
//Note that the loop only continues if c == l. Now imagine that our string
//is "2150000000", 2 == 2 (next), 1 == 1 (next), 5 > 4 as you can see,
//because 5 > 4 we can guarantee that the string will represent a bigger integer.
//Similarly, if our string was "2139999999", when we find out that 3 < 4,
//we can also guarantee that the integer represented will fit in an int.
for(i = 0; i < len; i++) {
c = s.charAt(i);
l = limit.charAt(i);
if(c > l) {
return false;
}
if(c < l) {
return true;
}
}
}
c = s.charAt(0);
if(len == 11) {
//If the first char is neither '+' nor '-' then 11 digits represent a
//bigger integer than 2147483647 (10 digits).
if(c != '+' && c != '-') {
return false;
}
limit = (c == '-') ? "-2147483648" : "+2147483647";
//Here we're applying the same logic that we applied in the previous case
//ignoring the first char.
for(i = 1; i < len; i++) {
c = s.charAt(i);
l = limit.charAt(i);
if(c > l) {
return false;
}
if(c < l) {
return true;
}
}
}
//The string passed all tests, so it must represent a number that fits
//in an int...
return true;
}
You may try apache utils
NumberUtils.isCreatable(myText)
See the javadoc here
You probably need to take the use case in account too:
If most of the time you expect numbers to be valid, then catching the exception is only causing a performance overhead when attempting to convert invalid numbers. Whereas calling some isInteger() method and then convert using Integer.parseInt() will always cause a performance overhead for valid numbers - the strings are parsed twice, once by the check and once by the conversion.
This is a modification of Jonas' code that checks if the string is within range to be cast into an integer.
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
int i = 0;
// set the length and value for highest positive int or lowest negative int
int maxlength = 10;
String maxnum = String.valueOf(Integer.MAX_VALUE);
if (str.charAt(0) == '-') {
maxlength = 11;
i = 1;
maxnum = String.valueOf(Integer.MIN_VALUE);
}
// verify digit length does not exceed int range
if (length > maxlength) {
return false;
}
// verify that all characters are numbers
if (maxlength == 11 && length == 1) {
return false;
}
for (int num = i; num < length; num++) {
char c = str.charAt(num);
if (c < '0' || c > '9') {
return false;
}
}
// verify that number value is within int range
if (length == maxlength) {
for (; i < length; i++) {
if (str.charAt(i) < maxnum.charAt(i)) {
return true;
}
else if (str.charAt(i) > maxnum.charAt(i)) {
return false;
}
}
}
return true;
}
If you are using the Android API you can use:
TextUtils.isDigitsOnly(str);
I believe there's zero risk running into an exception, because as you can see below you always safely parse int to String and not the other way around.
So:
You check if every slot of character in your string matches at least
one of the characters {"0","1","2","3","4","5","6","7","8","9"}.
if(aString.substring(j, j+1).equals(String.valueOf(i)))
You sum all the times that you encountered in the slots the above
characters.
digits++;
And finally you check if the times that you encountered integers as
characters equals with the length of the given string.
if(digits == aString.length())
And in practice we have:
String aString = "1234224245";
int digits = 0;//count how many digits you encountered
for(int j=0;j<aString.length();j++){
for(int i=0;i<=9;i++){
if(aString.substring(j, j+1).equals(String.valueOf(i)))
digits++;
}
}
if(digits == aString.length()){
System.out.println("It's an integer!!");
}
else{
System.out.println("It's not an integer!!");
}
String anotherString = "1234f22a4245";
int anotherDigits = 0;//count how many digits you encountered
for(int j=0;j<anotherString.length();j++){
for(int i=0;i<=9;i++){
if(anotherString.substring(j, j+1).equals(String.valueOf(i)))
anotherDigits++;
}
}
if(anotherDigits == anotherString.length()){
System.out.println("It's an integer!!");
}
else{
System.out.println("It's not an integer!!");
}
And the results are:
It's an integer!!
It's not an integer!!
Similarly, you can validate if a String is a float or a double but in those cases you have to encounter only one . (dot) in the String and of course check if digits == (aString.length()-1)
Again, there's zero risk running into a parsing exception here, but if you plan on parsing a string that it is known that contains a number (let's say int data type) you must first check if it fits in the data type. Otherwise you must cast it.
I hope I helped
several answers here saying to try parsing to an integer and catching the NumberFormatException but you should not do this.
That way would create exception object and generates a stack trace each time you called it and it was not an integer.
A better way with Java 8 would be to use a stream:
boolean isInteger = returnValue.chars().allMatch(Character::isDigit);
What you did works, but you probably shouldn't always check that way. Throwing exceptions should be reserved for "exceptional" situations (maybe that fits in your case, though), and are very costly in terms of performance.
This would work only for positive integers.
public static boolean isInt(String str) {
if (str != null && str.length() != 0) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) return false;
}
}
return true;
}
This works for me. Simply to identify whether a String is a primitive or a number.
private boolean isPrimitive(String value){
boolean status=true;
if(value.length()<1)
return false;
for(int i = 0;i<value.length();i++){
char c=value.charAt(i);
if(Character.isDigit(c) || c=='.'){
}else{
status=false;
break;
}
}
return status;
}
To check for all int chars, you can simply use a double negative.
if (!searchString.matches("[^0-9]+$")) ...
[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.
I have seen a lot of answers here, but most of them are able to determine whether the String is numeric, but they fail checking whether the number is in Integer range...
Therefore I purpose something like this:
public static boolean isInteger(String str) {
if (str == null || str.isEmpty()) {
return false;
}
try {
long value = Long.valueOf(str);
return value >= -2147483648 && value <= 2147483647;
} catch (Exception ex) {
return false;
}
}
When explanations are more important than performance
I noticed many discussions centering how efficient certain solutions are, but none on why an string is not an integer. Also, everyone seemed to assume that the number "2.00" is not equal to "2". Mathematically and humanly speaking, they are equal (even though computer science says that they are not, and for good reason). This is why the "Integer.parseInt" solutions above are weak (depending on your requirements).
At any rate, to make software smarter and more human-friendly, we need to create software that thinks like we do and explains why something failed. In this case:
public static boolean isIntegerFromDecimalString(String possibleInteger) {
possibleInteger = possibleInteger.trim();
try {
// Integer parsing works great for "regular" integers like 42 or 13.
int num = Integer.parseInt(possibleInteger);
System.out.println("The possibleInteger="+possibleInteger+" is a pure integer.");
return true;
} catch (NumberFormatException e) {
if (possibleInteger.equals(".")) {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it is only a decimal point.");
return false;
} else if (possibleInteger.startsWith(".") && possibleInteger.matches("\\.[0-9]*")) {
if (possibleInteger.matches("\\.[0]*")) {
System.out.println("The possibleInteger=" + possibleInteger + " is an integer because it starts with a decimal point and afterwards is all zeros.");
return true;
} else {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it starts with a decimal point and afterwards is not all zeros.");
return false;
}
} else if (possibleInteger.endsWith(".") && possibleInteger.matches("[0-9]*\\.")) {
System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with decimal point).");
return true;
} else if (possibleInteger.contains(".")) {
String[] partsOfPossibleInteger = possibleInteger.split("\\.");
if (partsOfPossibleInteger.length == 2) {
//System.out.println("The possibleInteger=" + possibleInteger + " is split into '" + partsOfPossibleInteger[0] + "' and '" + partsOfPossibleInteger[1] + "'.");
if (partsOfPossibleInteger[0].matches("[0-9]*")) {
if (partsOfPossibleInteger[1].matches("[0]*")) {
System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with all zeros after the decimal point).");
return true;
} else if (partsOfPossibleInteger[1].matches("[0-9]*")) {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the numbers after the decimal point (" +
partsOfPossibleInteger[1] + ") are not all zeros.");
return false;
} else {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'numbers' after the decimal point (" +
partsOfPossibleInteger[1] + ") are not all numeric digits.");
return false;
}
} else {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'number' before the decimal point (" +
partsOfPossibleInteger[0] + ") is not a number.");
return false;
}
} else {
System.out.println("The possibleInteger="+possibleInteger+" is NOT an integer because it has a strange number of decimal-period separated parts (" +
partsOfPossibleInteger.length + ").");
return false;
}
} // else
System.out.println("The possibleInteger='"+possibleInteger+"' is NOT an integer, even though it has no decimal point.");
return false;
}
}
Test code:
String[] testData = {"0", "0.", "0.0", ".000", "2", "2.", "2.0", "2.0000", "3.14159", ".0001", ".", "$4.0", "3E24", "6.0221409e+23"};
int i = 0;
for (String possibleInteger : testData ) {
System.out.println("");
System.out.println(i + ". possibleInteger='" + possibleInteger +"' isIntegerFromDecimalString=" + isIntegerFromDecimalString(possibleInteger));
i++;
}

Categories