So I'm making a Binary to Decimal converter and I'm supposed to catch the invalid character if the user inputs an illegal argument. I believe I have the correct method for catching any characters that aren't 0 or 1. However, when I try to implement this method into my primary method parseBinary, it says that it "Cannot Find Symbol" for illegal(iChar).
I can't add any more parameters to parseBinary because the user is only supposed to enter one string of 0's and 1's. I'm curious if I made this method for nothing because of this restriction, but this is the only way I know of going about it. I'm a novice. Any/all help is very appreciated.
public static int parseBinary(String binary) throws NumberFormatException {
if (!isBinary(binary)) {
throw new NumberFormatException("Invalid Format for a Binary String - Illegal character: " + illegal(iChar));
}
int power = 0;
int decimal = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += Math.pow(2, power);
}
power++;
}
return decimal;
}
public static boolean isBinary(String binary) {
for (char ch : binary.toCharArray()) {
if (ch != '1' && ch != '0'){
return false;
}
}
return true;
}
public static char illegal(String iChar)
{
char test = 0;
char arr[] = iChar.toCharArray();
for(char cha : arr)
{
if (cha != '1' && cha != '0')
{
test = cha;
}
}
return test;
}
As @mureinik said instead of doing
throw new NumberFormatException("Invalid Format for a Binary String - Illegal character: " + illegal(iChar));
you must pass binary to the method illegal
change it to
throw new NumberFormatException("Invalid Format for a Binary String - Illegal character: " + illegal(binary));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.