English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

java.lang.String [ ] data ={ "1", "8", "papa", "4" };

this is part of a code which includes both integers and strings;

i need the code to tell me data[0] is an ineger (although its been defined as a string)
but data [2] is NOT an integer

2007-09-11 07:46:15 · 3 answers · asked by CuriousStar 1 in Computers & Internet Programming & Design

3 answers

for( int ctr=0; ctr try{
int i=Integer.parseInt(data[ctr]);
System.out.println( data[ctr]+" is an integer" );
}catch( NumberFormatException e ){
System.out.println( data[ctr]+" is a string" );
}
}

an exception may be thrown at line 3 when you try to parse the string to an integer. the program then executes the catch block. in a try, catch block statements below the statement where an exception occurs is not performed. alternatively you could do this:

for( int ctr=0; ctr boolean isNumber=true;
String current=data[ctr];
for(int ctr1=0; ctr1 if( ctr1==0 && current.charAt (ctr1) == '-' && current.length ()>1 ){
continue;
}else{
if( !Character.isDigit (current.charAt (ctr1) ) ){
boolean isNumber=false;
}
}
if( isNumber ){
System.out.println(current + "is an integer." );
}else{
System.out.println(current + "is a string." );
}
}

kindly check the syntax. :p

2007-09-11 12:44:17 · answer #1 · answered by rodette p 3 · 0 0

You could iterate through each entry and "try" to cast the object to an Integer object. Setup a catch for NumberFormatException to handle non-integer values on the cast.

Integer myInteger = null;
String[] data = {"1","2","papa","8"};
for (int i = 0; i < data.length; i++) {
try {
myInteger = new Integer(data[i]);
System.out.println("Element " + i + " (value = " + myInteger.intValue() + ") is an integer.");
} catch (NumberFormatException nfe) {
System.out.println("Element " + i + " (value = " + data[i] + ") is an integer.");
}
}

2007-09-11 14:57:58 · answer #2 · answered by Jim Maryland 7 · 0 0

you could determine it by parsing it example it

try
{
int one=Integer.parseInt(data[0]);
}
catch(Exception e)
{

}

this is just a sample but note at the "Integer.parseInt()" part...
id theres an error then it isnt a integer... :D ok? hope that helps..

2007-09-11 21:59:38 · answer #3 · answered by Anonymous · 0 0

fedest.com, questions and answers