gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:11:25 25 4
gpt4 key购买 nike

输出应该是二进制到十进制的转换。当我运行这个程序并输入(例如)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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com