输出应该是二进制到十进制的转换。当我运行此程序并输入(例如)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;
}
}
答案 0 :(得分:3)
您正在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());
}
}
因此它当然会执行输入中字符数的次数。将呼叫转移到for error(s)
。
答案 1 :(得分:0)
你不应该尝试重新发明已经完成的事情。只需使用Integer#parseInt(String s, int radix)即可:
public class Bin2Dec {
public static void main (String[] args){
System.out.print("Enter a binary string of 0's and 1's: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int decoded = Integer.parseInt(input, 2);
System.out.println(decoded);
}
}
答案 2 :(得分:0)
只需删除'for'循环,如下所示:
//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 (Exception e) {
System.out.println("There is an error in the entered binary
string:"+e.getMessage());
}
}
//}