[英]JAVA: Method can't find value from another method
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).我相信我有捕获任何非 0 或 1 字符的正确方法。但是,当我尝试将此方法实现到我的主要方法 parseBinary 中时,它说它“无法找到非法符号(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.我无法向 parseBinary 添加更多参数,因为用户只应该输入一个由 0 和 1 组成的字符串。 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正如@mureinik 所说的,而不是做
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.