java - 为什么这个程序会根据用户输入的位数重复答案?

标签 java exception binary decimal extend

输出应该是二进制到十进制的转换。当我运行这个程序并输入(例如)101时,它会打印答案3次,因为101是3位数字。我该如何解决?我只需要一个答案。请帮忙

    import java.util.Scanner;

    public class Bin2Dec {

public static void main (String[] args){
//Convert the input string to their decimal equivalent.
    //Open scanner for input.
        Scanner input = new Scanner(System.in);
        //Declare variable s.
        String s;

        //Prompt user to enter binary string of 0s and 1s.
        System.out.print("Enter a binary string of 0's and 1's: ");
        //Save input to s variable.
        s = input.nextLine();

        //Create a loop using the length of user input as the maximum number.
        for (int i=0;i< s.length();i++){
            try {
             System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
              } catch (BinaryFormatException e) {
                System.out.println("There is an error in the entered binary string:"+e.getMessage());
              }
            }
          }

          public static int error(String parameter) throws BinaryFormatException {
            int tot = 0;
            for (int i = parameter.length(); i > 0; i--) {
              char c = parameter.charAt(i - 1);
              if (c == '1') tot += Math.pow(2, parameter.length() - i);
              else if (c != '0') throw new BinaryFormatException("'"+c+"' is not a binary digit");
            }
            return tot;
          } 
        }

最佳答案

您正在 for 循环中调用该方法:

for (int i=0;i< s.length();i++){
  try {
    System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
  } catch (BinaryFormatException e) {
    System.out.println("There is an error in the entered binary string:"+e.getMessage());
  }
}

因此,它当然会执行与输入中的字符数一样多的次数。将对 error(s) 的调用移出 for 循环。

关于java - 为什么这个程序会根据用户输入的位数重复答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728222/

相关文章:

python - 如何使用 python lambdas 捕获异常

java - 不能使用 AuthenticationException 的子类

Python NumPy 'Expected an input array of unsigned byte data type'

java - 如何将静态 Icon 与动画 Icon 结合起来

c# - 包装一个 IEnumerable 并捕获异常

c++ - 如何在 C++ 中求和/异或二进制字符串?

python - 在 Python 3 中将二进制字符串转换为字节数组

java - Spring 数据 JPA : Specification with "like" and Long

java - 如何强制 CLOSE_WAIT 停止

启动 jenv 后 java_home 仍然指向最新版本的 java