JAVA:方法无法从其他方法中找到价值 [英] JAVA: Method can't find value from another method

查看:34
本文介绍了JAVA:方法无法从其他方法中找到价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在制作一个二进制到十进制的转换器,并且如果用户输入了非法参数,我应该捕获无效字符.我相信我有正确的方法来捕获任何非0或1的字符. 但是,当我尝试将这种方法实现到我的主要方法parseBinary中时,它说它代表非法"(iChar)找不到符号".

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).

我无法再向parseBinary添加任何参数,因为用户只能输入一个0和1的字符串.我很好奇我是否因为这种限制而一无所获,但是这是我知道的唯一方法.我是新手.任何/所有帮助都非常感谢.

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;
}

推荐答案

正如@mureinik所说 而不是做

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

将其更改为

throw new NumberFormatException("Invalid Format for a Binary String - Illegal character: " + illegal(binary));

这篇关于JAVA:方法无法从其他方法中找到价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆