By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,836 Members | 1,703 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,836 IT Pros & Developers. It's quick & easy.

I'm new, basic conversion question

P: 2
hello.

I'd like to ask how to determine if a String could also be an Integer:
I have to determine from, say "boo" "b123" "20" "132" which are numbers.

thanks..
Jan 26 '09 #1
Share this Question
Share on Google+
12 Replies


cordeo
P: 16
Have a look at Java 2 Platform SE v1.3.1: Class Integer)

and catch the NumberFormatException which will by thrown if the string does not contain a parsable integer.
Jan 26 '09 #2

P: 2
thanks a lot.. I made it so, in a try{}, and works fine:

Expand|Select|Wrap|Line Numbers
  1. if (args[i].compareTo(Integer.toString(Integer.parseInt(args[i]))) == 0)
but is there any other way which is more simple?
Jan 26 '09 #3

cordeo
P: 16
There is no need for conversion back to String and doing a comparison with compareTo. An elegant solution is like this:
Expand|Select|Wrap|Line Numbers
  1.         // Loop through all the command line arguments
  2.         for (int i = 0; i < args.length; i++) {
  3.             // Get the command line parameter as a String
  4.             String potentialNumber = args[i];
  5.  
  6.             // Stores the parsed command line argument
  7.             int j;
  8.  
  9.             try {
  10.                 // Try to read the argument as an integer
  11.                 j = Integer.parseInt(potentialNumber);
  12.             } catch (NumberFormatException e) {
  13.                 // Output an error message on the console
  14.                 System.out.println
  15.                     ( "Argument " + i
  16.                     + " is not an integer "
  17.                     + "(" + e.getMessage() + ")!"
  18.                     );
  19.  
  20.                 // Continue from for (line 2 above) with
  21.                 // the next command line argument
  22.                 continue;
  23.             }
  24.  
  25.             // No exception was thrown, so
  26.             // we have found an integer
  27.             System.out.println
  28.                 ( "Argument " + i
  29.                 + " is a fine integer number: " + j
  30.                 );
  31.         }
  32.  
Jan 26 '09 #4

BSCode266
P: 38
If you want to make sure there are no letters or any other symbols I would suggest the use of a method in the Character wrapper class.

Example:
Expand|Select|Wrap|Line Numbers
  1. //Loop just as the previous example to go through all args.
  2. for (int i = 0; i < args.length; i++) {
  3.      //Temporary String to save the digits in.
  4.      String temp;
  5.  
  6.      //Loop through a single args.
  7.      for(int j = 0; j < args[i].length(); j++){
  8.           //Check for digits in the whole args[i].
  9.           if(Character.isDigit(args[i].charAt(j))){
  10.                //Add the found digit to the temporary String.
  11.                temp += args[i].charAt(j);
  12.           }
  13.      }
  14.      try{
  15.           int x = Integer.parseInt(temp);
  16.      }catch (NumberFormatException e) {
  17.       //See previous example.
  18.      }
  19. }
Jan 26 '09 #5

Expert 10K+
P: 11,448
@BSCode266
That approach doesn't work; although the String "999999999999999999999" contains all digits, it is not an integer in Java's terms (too big to fit in four bytes).

kind regards,

Jos
Jan 26 '09 #6

cordeo
P: 16
The approach does work, but integer is (of course) limited to at most Integer.MAX_VALUE. If you need support for larger numbers, use Long (Long (Java Platform SE 6)) or even BigInteger (BigInteger (Java Platform SE 6)).

Long is also limited, but can hold larger numbers than integer. BigInteger is not limited at all, but needs more memory.

The class Long has a parseLong method. BigInteger has no such method, but you can use
Expand|Select|Wrap|Line Numbers
  1. new BigInteger("999999999999999999999");
  2.  
Jan 26 '09 #7

Expert 10K+
P: 11,448
@cordeo
Yup, and the op wanted to know whether or not a String could textually represent an Integer (see the first post). Your approach doesn't check that.

kind regards,

Jos
Jan 26 '09 #8

cordeo
P: 16
@JosAH
This sounds quite strange. I'm afraid I don't understand you. BSCode266 suggests possible extra constraints, but keeps this line (from my original code example):
@BSCode266
Integer.parseInt() will never accept anything that does not fit an Integer, and absolutely performs the required check. I really don't understand why you think my approach doesn't check that. Try it yourself: your input string "999999999999999999999" will be refused by my own code example as well as by the code example of BSCode266 (in both cases, Integer.parseInt throws a NumberFormatException).

For the case you (or possibly the original poster) deliberately want(s) larger (mathematical) integer numbers, I suggested Long and BigInteger as alternatives.

A problem with the approach of BSCode266 is that he silently ignores non-digit characters, so "23abc4" will be accepted as 234, which is incorrect. The scoping is incorrect as well. int x = Integer.parseInt... is inside the try-block and cannot be referenced after the try. That is why I placed the int j; declaration before try.
Jan 26 '09 #9

Expert 10K+
P: 11,448
@cordeo
You're right: I misread your and other replies; I apologize for that; imho it is silly to explicitly check for digits and optionally discard the non-digits. Simply feed the String to the Integer.parseInt() method and let it throw an exception when needed.

kind regards,

Jos
Jan 27 '09 #10

Expert 100+
P: 785
@cordeo
Yes, he should break the loop at the first non-digit he found. I guess he wants to simulate other languages like C++ which will stop parsing when they find a non-digit and return the converted number at string begin (in this case 23).

But what he probably also should care about are 2 more cases:
a) Leading and trailing spaces. Integer.parseInt(" 017") and Integer.parseInt("017 ") throws an exception. So you should probably trim the string.
b) hexadecimal and octal numbers. Integer.parseInt("017") returns 17, but it is an octal number, because it begins with a leading zero. So the correct answer would be 15. Maybe you should think of also allowing hexadecimal numbers, like "0x1a".

Use of regular expressions to shorten algorithm:
@BSCode266
A nasty thing of this loop is that it unnecessarily creates and allocates many temporary strings in memory. Consider StringBuilder class (or StringBuffer for older JDKs).

Anyway, there is no need to make a loop and parse for characters, you can do it simpler in a single line with help of regular expression:
Expand|Select|Wrap|Line Numbers
  1. String temp = args[i].replaceFirst("(\\d*).*", "$1")
  2.  
Jan 27 '09 #11

cordeo
P: 16
@JosAH
I fully agree. That is what I posted originally, and also why I noticed a problem in the approach of BSCode266.

On the other hand, I think it is useful to understand that Integer.parseInt() uses the Character class internally anyway.
Jan 27 '09 #12

cordeo
P: 16
Suggestion a) is nice. Concerning regular expressions, they might not be very suitable for the original poster (who was not even familiar with parseInt). Let's not make it too difficult for some who is new to Java.

@chaarmann
017 as octal number and 0x1a as hexadecimal number are valid when directly written in Java. For example, a ==b, a == c and b == c after these 3 lines of code:
Expand|Select|Wrap|Line Numbers
  1.     int a = 017;
  2.     int b = 0xf;
  3.     int c = 15;
  4.  
That is quite different from Integer.parseInt(String) which is documented to only work with base-10 numbers. For octal and hexadecimal numbers, there is Integer.parseInt(String, int), but though leading zero's are accepted, the 'x' of hexadecimal numbers is not, so a special check is necessary.

There is
-3 // decimal, accepted by parseInt
+4 // decimal, accepted by parseInt
245 // decimal, accepted by parseInt
-03 // octal, accepted by parseInt
+04 // octal, accepted by parseInt
0245 // octal, accepted by parseInt
-0x3 // hex, not accepted by parseInt ('x' not allowed)
+0x4 // hex, not accepted by parseInt ('x' not allowed)
0x245 // hex, not accepted by parseInt ('x' not allowed)

Expand|Select|Wrap|Line Numbers
  1.             // Get the command line parameter as a String
  2.             String potentialNumber = args[i];
  3.  
  4.             // Stores the parsed command line argument
  5.             int j;
  6.  
  7.             try {
  8.                 if (potentialNumber.length() == 0) {
  9.                     throw new NumberFormatException("Empty string!");
  10.                 }
  11.  
  12.                 // Start at index 0
  13.                 int idx = 0;
  14.  
  15.                 // Skip (for now) leading + or - sign
  16.                 char first = potentialNumber.charAt(0);
  17.                 if (first == '+' || first == '-') {
  18.                     idx++;
  19.                 }
  20.  
  21.                 if (potentialNumber.charAt(idx) == '0') { // Octal or Hex?
  22.                     idx++;
  23.                     if (potentialNumber.charAt(idx) == 'x') { // Hex?
  24.                         idx++;
  25.                         // parseInt can't handle the 'x', so we only provide
  26.                         // everything after the 'x' to parseInt
  27.                         j = Integer.parseInt
  28.                                 (potentialNumber.substring(idx), 16);
  29.                         // We possibly skipped a - sign, so check for that
  30.                         if (first == '-') {
  31.                             j *= -1;
  32.                         }
  33.                     } else { // Octal
  34.                         // parseInt can handle the complete octal
  35.                         // potentialNumber, including a possible + or - sign.
  36.                         j = Integer.parseInt(potentialNumber, 8);
  37.                     }
  38.                 } else {
  39.                     // Try to read the argument as a decimal integer
  40.                     // parseInt can handle the complete decimal
  41.                     // potentialNumber, including a possible + or - sign.
  42.                     j = Integer.parseInt(potentialNumber);
  43.                 }
  44.             } catch (NumberFormatException e) {
  45.                 // Output an error message on the console
  46.             }
  47.  
Jan 27 '09 #13

Post your reply

Sign in to post your reply or Sign up for a free account.