473,396 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

I'm new, basic conversion question

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
12 1529
cordeo
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
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
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
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
JosAH
11,448 Expert 8TB
@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
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
JosAH
11,448 Expert 8TB
@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
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
JosAH
11,448 Expert 8TB
@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
chaarmann
785 Expert 512MB
@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
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
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

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

Similar topics

41
by: Psykarrd | last post by:
I am trying to declare a string variable as an array of char's. the code looks like this. char name; then when i try to use the variable it dosn't work, however i am not sure you can use it...
14
by: luis | last post by:
Are basic types (int, long, ...) objetcs or not? I read that in C# all are objects including basic types, derived from Object class. Then in msdn documentation says that boxing converts basic...
5
by: Alex Bilger | last post by:
Is there a way to override Visual Basic Implicit Conversions ? for example: ---- Dim s As String Dim i As Integer i=s s=i ---
16
by: Jesse Liberty | last post by:
I am writing a new book on Visual Basic 2005, targeted at VB6 programmers, and to some degree VB.NET 1.x programmers. I'd like to sign up a (limited) number of volunteers to read the book and...
9
by: pauldepstein | last post by:
#include <iostream> using namespace std; int main() { int testNum; char *ptr; testNum = 1; ptr = (char*)(&testNum);
97
by: Master Programmer | last post by:
An friend insider told me that VB is to be killled off within 18 months. I guess this makes sence now that C# is here. I believe it and am actualy surprised they ever even included it in VS 2003 in...
4
by: Chris Asaipillai | last post by:
Hi there My compay has a number of Visual Basic 6 applications which are front endeed onto either SQL Server or Microsoft Access databases. Now we are in process of planning to re-write these...
6
by: ashokbio | last post by:
I want to create an associative array, similar to PERL language, using Visual Basic 6. Example: Using PERL %A = ("A"=>"Apple","B"=>"Banana"); i.e., A is associated to the word Apple and B...
4
by: Goran Djuranovic | last post by:
Hi all, I am experiencing a strange thing happening with a "designer.vb" page. Controls I manually declare in this page are automatically deleted after I drop another control on a ".aspx" page. -...
21
by: REH | last post by:
It it permissible to use the constructor style cast with primitives such as "unsigned long"? One of my compilers accepts this syntax, the other does not. The failing one chokes on the fact that the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.