I am trying to determine whether a string contains a positive int or not. My code is:
public void isInt(String str) throws NotIntException{
String integer=str.replaceAll("\\d","");
System.out.println(integer);
if (!integer.equals("")){
throw new NotIntException("Wrong data type-check fields where an integer"+
" should be.");
}//end if
if (integer.equals("-")){
System.out.println(integer);
throw new NotIntException("Error-Can't have a negative count.");
}//end if
}//end method
I am testing this with a string “-1”, which should, after the replaceAll(), become “-“. This should enter both if-statements. But it only enters the first. I tried it with the == comparison too, just in case, but it didn’t work either. What’s odd to me is that whether I look to fulfill the second if-statement’s condition or to fulfill its negation [i.e., !integer.equals(“-“)], the program still doesn’t enter the if….
Thanks, usually my comparison issues are just me missing something basic, but I really don’t see anything here…
Since you are throwing an Exception in your first if, so, your 2nd if will not even be tested.
If your code enters the first
if, it will not execute further.But, why are you using this approach for your problem.
You can easily use
Integer.parseIntto check for validinteger. And then if it is valid, then test whether itsless than 0. It would be far easier and readable.