Can somebody please explain what is going on here? Why is the "non-static variable this cannot be referenced from a static context." appearing in this code? I have tried changing the parseBinary to non-static. I have tried changing the BinaryFormatException class to static... (not allowed). My understanding of this error is very weak. I know I can usually swap some static and public words around and get it to work right. No such luck with this. This is a homework question... but the work does not revolve around the error. It has to do with creating a custom exception class that is thrown when a binary string is incorrectly formed. So while my question will help me answer the problem, it will not give me the answer.
public class binaryToDecimal {
public static void main(String[] args) {
try {
System.out.println(parseBinary("10001"));
System.out.println(parseBinary("101111111"));
} catch (BinaryFormatException ex) {
ex.getMessage();
}
}
public static int parseBinary(String binaryString)
throws BinaryFormatException {
int value = 0;
for (int i = 0; i < binaryString.length(); i++) {
char ch = binaryString.charAt(i);
if (ch != '0' && ch != '1') {
throw new BinaryFormatException(String message);
value = 0;
} else
value = value * 2 + binaryString.charAt(i) - '0';
}
return value;
}
class BinaryFormatException extends Exception {
public BinaryFormatException(String message) {
super(message);
}
}
}
It looks like you've defined
BinaryFormatExceptionas an inner class to your public classbinaryToDecimal. That means that you need an instance ofbinaryToDecimalto have an instance ofBinaryFormatException. However, you are in thestaticcontext of theparseBinarymethod. There is no instance ofbinaryToDecimal.You have two choices:
BinaryFormatExceptionclassstatic.BinaryFormatExceptionclass code outside of thebinaryToDecimalclass.