I'm trying to figure out how to catch a numberformat exception error within my code such that if the user inputs a letter within a string and my program tries to parse it to an int my program won't throw up an error but instead stop and return a Boolean value. I'm also trying to understand that if the try statement works I'd like it to continue to execute the following code.
if (counter == 3) {
int compare;
boolean check = true;
String[] newip = IpAddress.split("\\.");
if (newip.length == 4) {
for (int index = 0; index < newip.length; index++) {
//There should be a try statement here.
// if the try statement fails then I'd like for it to catch
// the numberformatexception and evaluate my boolean to
//false;
//but if it passes I'd like for it to continue to execute
//the following code.
compare = Integer.parseInt(newip[index]);
if (compare >= 0 & (compare <= 255)) {
check = true;
}
else{
check = false;
}
}
if (check)
return true;
else
return false;
}
else {
check = false;
return check;
}
}
else{
return false;
}
}
Surround that line with try/catch:
try {
compare = Integer.parseInt(newip[index]);
} catch (NumberFormatException e) {
check = false;
}
and then:
if (check) {
if (compare >= 0 & (compare <= 255)) {
check = true;
} else {
check = false;
}
} else {
return false;
}
Instead of catching NumberFormatException, you can use NumberUtils from commons-lang 3.x to check if the input is a number.
NumberUtils.isNumber(newip[index])
However as per the documentation, it would be deprecated in 4.x and you would need to use isCreatable
NumberUtils.isCreatable(newip[index])
Related
Where is the problem? If I use a variable it works just fine, but I am missing something.
public boolean xyzThere(String str) {
if (str.length() > 2){
if(str.startsWith("xyz")){
return true;
} else {
for (int i = 1; i < str.length() - 2; i++){
if(str.substring(i, i + 3).equals("xyz") && !str.substring(i - 1, i).equals(".")) {
return true;
} else {
return false;
}
}
}
} else {
return false;
}
}
This condition needs a return statement as the code inside for loop may not be reachable.
else {
for (int i = 1; i < str.length() - 2; i++) {
if (str.substring(i, i + 3).equals("xyz") && !str.substring(i - 1, i).equals(".")) {
return true;
} else {
return false;
}
}
}
Because it might be possible that none of your outer if condition succeed , So Compiler is making sure that your program doesn't get stuck into the function , by throwing the missing return statement error
So try this way :
if(condition){
return false;
}
elseif(condition){
return true;
}
return false; <--- Now compiler is assured that function will return something
Assuming the return type is boolean
The Java compiler will not evaluate the conditions to determine if one of if condition and an else if condition will be guaranteed to run.
Without the conditions, the compiler see the possibility of neither condition being true, and in that case, nothing is returned. There are not return statements past the else if. This occurs even if we see that logically one of them will be true.
Just turn your else if into an else to satisfy the compiler.
else {
return false;
}
Now the compiler will see that there is a return statement in all possible execution paths.
In these cases, sometimes I comment out the condition to let readers know the real intent.
else // if (str.length() < 3)
{
return false;
}
Update:
Something similar is occurring inside the for loop. The compiler won't assume that at least one iteration of a for loop will occur. If the for loop body is never entered, then the else block ends, and the body of the outer if block ends without a return statement`.
You must provide a return statement after the for loop, in case the for loop is never entered.
Now it is compiling:
public boolean xyzThere(String str) {
if (str.length() < 3){
return false;
} else {
if(str.startsWith("xyz")){
return true;
} else {
for (int i = 1; i < str.length() - 2; i++){
if(str.substring(i, i + 3).equals("xyz") && !str.substring(i - 1, i).equals(".")) {
return true;
} else {
}
}
return false;
}
}
}
I have a method that is being called to validate that an IP address is assignable. No matter what I pass to it, it is always returning true. What do I need to set the return as to get this method working properly?
public boolean checkValidIPClass(String x) {
for (int i = 0; i < 4; i++) {
try {
if (retString.equals("A")) {
if ((intParts[1] == 0) && (intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[1] == 255) && (intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("B")) {
if ((intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("C")) {
if (intParts[3] == 0)
return false;
if (intParts[3] == 255)
return false;
}
} //ends try
catch (NumberFormatException nfe) {
return false;
} //ends catch
} //ends for
return true;
}
retString is making it to the method and is a string that was returned from another method that checks what class the IP address is and assigns it, this was verified with a print statement. Thanks!
EDIT: How has this been answered and downvoted? My question wasn't about comparing the strings, it was about the method always returning true even when I know the if statements should be catching the error and returning false?
EDIT2: Updated my code.
I don't get why you're doing a loop, but you could try this:
public boolean checkValidIPClass(String ipClass, String ipAddress)
{
if (ipClass.contentEquals("A"))
{
if (ipAddress.endsWith("0.0.0") || ipAddress.endsWith("255.255.255"))
return false;
}
else if (ipClass.contentEquals("B"))
{
if (ipAddress.endsWith("0.0") || ipAddress.endsWith("255.255"))
return false;
}
else if (ipClass.contentEquals("C"))
{
if (ipAddress.endsWith("0") || ipAddress.endsWith("255"))
return false;
}
return true;
}
Since you're just checking the ending array parts of the IP address, you don't need to break it into an array, just leave it as a string.
And keep in mind that this would only satisfy IPv4 formatted IP addresses. It will not work for IPv6 formatted addresses
Not keen on using the parseInteger solution, it is ugly, and as Joshua Bloch says you should "Use exceptions only for exceptional conditions". Of course, I can use something like block of code below, but it doesn't guarantee it is an Integer.
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
"Use exceptions only for exceptional conditions" is a good practice to follow in general, but it's not a hard-and-fast rule. I think that this is one of the cases where using exceptions is better than the alternatives.
Since parseInteger() can return any possible int value, you can't use any other return value to indicate failure. If you know you're never going to process a particular value (such as -1 or -2147483648), you can return that as a sentinel value to indicate a parse failure.
The only alternative is to return a boolean indicating success or failure and to store the parsed value into a parameter. However, since function calls are always pass-by-value in Java, you'd need to create a new class to do this:
public class IntWrapper
{
int value;
}
...
public static boolean myParseInt(String s, IntWrapper outValue)
{
try
{
outValue.value = Integer.parseInt(s);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}
...
IntWrapper value = new IntWrapper();
if (myParseInt(value))
{
// Use value.value
}
else
{
// Parsing failed
}
Given these alternatives, I think the simplest usage is just to use exceptions and deal with them appropriately, even though non-numeric input may not necessary be an "exceptional" condition.
I'd leave it with exception but if you REALLY want solution without exception you can copy method parseInt() from this site with java internal classes and change it a little bit
(You can modify it a little bit more, since you do not need result)
public static false isValidInt(String s, int radix)
throws NumberFormatException
{
if (s == null) {
return false;
}
if (radix < Character.MIN_RADIX) {
return false;
}
if (radix > Character.MAX_RADIX) {
return false;
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else
return false;
if (len == 1) // Cannot have lone "-"
return false;
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
return false;
}
if (result < multmin) {
return false;
}
result *= radix;
if (result < limit + digit) {
return false;
}
result -= digit;
}
} else {
return false;
}
return true;
}
You could use:
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 <= '/' || c >= ':') {
return false;
}
}
return true;
}
Already answered here: What's the best way to check to see if a String represents an integer in Java?
I develop a function that reject number starting with 00 and 99.
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
if (number.charAt(0)==00){
}
return false;
}
How can i implement this function properly.
that if statement will always returns false.
One solution:
if (number.trim().startsWith("00") || number.trim().startsWith("99")){
System.out.println("not valid");
}
Use .startsWith():
if (number.startsWith("00") || number.startsWith("99")) ...
.charAt() returns a single character, not a string.
(out of sheer curiosity, why this? code_postal.getText().toString(); From the name of .getText(), you'd have figured out that it already returned a String... Bah.)
EDIT So, on demand, another version which checks by converting to an int first...
final int begin = Integer.parseInt(number.subString(0, 2));
if (begin % 99 == 0) // can only be true if number is 0 or 99
// etc
If I understand your question specially heading "lies between 00 && 99" you want this
try
{
String s = "45Abc";
Integer i = Integer.parseInt(s.substring(0,2));
if (i>00 && i<99)
System.out.println("True");
}catch (NumberFormatException e)
{
// TODO Auto-generated catch block
System.out.println("First two characters are not numbers");
}
Use your logic look like below
private boolean isValid(String str) {
if (str == null)
return false;
String tempStr = null;
try {
if (str.length() > 2) {
tempStr = str.substring(0, 2);
} else {
tempStr = str;
}
int number = Integer.parseInt(tempStr);
if (number >= 0 && number <= 99) {
return false; //in between 0 to 99
} else {
return true;
}
} catch (NumberFormatException e) {
}
return false;
}
You can use String class indexOf() method :
if (number.indexOf("00")==0 || number.indexOf("99")==0)
EDITED: - You need this as I understood from your question subject line "Check first two digit number lies between 00 && 99".
public static boolean isValid(String name) {
boolean isValid = true;
if(name.length()>2){
name = name.substring(0, 2);
}
try {
int number = Integer.parseInt(name);
if(number>-1 || number<100){
isValid = false;
}
}
catch(Exception e){
isValid = false;
}
return isValid;
}
To check if the Entered number starts with "00" or "99"
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
if(number.startsWith("00") || number.startsWith("99")){
return true;
}
return false;
}
To check if the Entered number is between "00" and "99"
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
String firstTwoDigits = number.substring(0,2);
if (Integer.valueOf(firstTwoDigits )>=0 && Integer.valueOf(firstTwoDigits )<=99){
return true;
}
return false;
}
Note: The title of your question and description are different. hence two answers.
Just to be different (and inefficient and impenetrable):
return !number.matches("^\s?(00|99).+");
Let's say I have a boolean method that uses an if statement to check whether the return type should be true or false:
public boolean isValid() {
boolean check;
int number = 5;
if (number > 4){
check = true;
} else {
check = false;
}
return check;
And now, I want to use this method as a parameter of an if statement in a different method:
if(isValid == true) // <-- this is where I'm not sure
//stop and go back to the beginning of the program
else
//continue on with the program
So basically what I'm asking is, how do I check what the return type of the boolean method within the parameters of an if statement is? Your answers are deeply appreciated.
Since it's a method, to call it you should use parens afterwards, so your code would then become:
if(isValid()) {
// something
} else {
//something else
}
public boolean isValid() {
int number = 5;
return number > 4;
}
if (isValid()) {
...
} else {
...
}
You should be able to just call the function within the IF condition so:
if (isValid()) {
}else {
}
Since isValid() returns a boolean the condition will be evaluated right away. I have heard it is better form to create a local var just before you test you condition.
boolean tempBoo = isValid();
if (tempBoo) {
}else {
}
- If statement accepts only boolean value.
public boolean isValid() {
boolean check = false; // always intialize the local variable
int number = 5;
if (number > 4){
check = true;
} else {
check = false;
}
return check;
}
if(isValid()){
// Do something if its true
}else{
// Do something if its false
}
if (isValid()) {
// do something when the method returned true
} else {
// do something else when the method returned false
}
You can use :
if(isValid()){
//do something....
}
else
{
//do something....
}
public boolean isValid() {
boolean check;
int number = 5;
if (number > 4){
check = true;
} else {
check = false;
}
return check;
How can you do this whole method without boolean check?
So how to get rid of.. check = true, check = false, return check stuff?