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 BinaryFormatException
as an inner class to your public class binaryToDecimal
. That means that you need an instance of binaryToDecimal
to have an instance of BinaryFormatException
. However, you are in the static
context of the parseBinary
method. There is no instance of binaryToDecimal
.
You have two choices:
BinaryFormatException
class static
.BinaryFormatException
class code outside of the binaryToDecimal
class.