java - 不使用 parseint 或数组的二进制到十进制转换器
问题描述
使字符串索引超出范围,但我不明白为什么我经历了大约 50 次
import java.util.Scanner;
public class binary {
public static void main(String[] args) {
System.out.println("Enter the first binary number");
Scanner keyboard = new Scanner(System.in);
String num1 = keyboard.next();
//System.out.println("Enter the second binary number");
//String num2 = keyboard.next();
int total = 0;
for(int i = num1.length(); i>0;i--) {
if(num1.charAt(i) == 1) {
total += 2*i;
}
}
if(num1.charAt(3) == 1) {
total -= 1;
}
System.out.println(total);
}
}
解决方案
这是您尝试做的事情的完整解决方案,包括一组测试:
class binary {
private static int binaryToInt(String binary) {
int total = 0;
for (int i = 0 ; i < binary.length(); i++) {
total *= 2;
if (binary.charAt(i) == '1')
total += 1;
}
return total;
}
private static void test(String binary, int expected) {
int n = binaryToInt(binary);
String rightWrong = "right";
if (n != expected) {
rightWrong = String.format("WRONG! (should be %d)", expected);
System.out.printf("%s -> %d is %s\n", binary, n, rightWrong);
}
public static void main(String[] args) {
test("0", 0);
test("1", 1);
test("10", 2);
test("100", 4);
test("111", 7);
test("0000111", 7);
test("1010101010", 682);
test("1111111111", 1023);
System.out.println("");
// test sanity check
System.out.println("This last test should fail (we are just testing the test method itself here)...");
test("1010101010", 0);
}
}
结果:
0 -> 0 is right
1 -> 1 is right
10 -> 2 is right
100 -> 4 is right
111 -> 7 is right
0000111 -> 7 is right
1010101010 -> 682 is right
1111111111 -> 1023 is right
This last test should fail (we are just testing the test method itself here)...
1010101010 -> 682 is WRONG! (should be 0)
您的代码中的一个重要问题尚未在评论或早期答案中得到解决。请注意这一行与代码中的行:
if (binary.charAt(i) == '1')
您正在测试数值1
,这永远不会是true
因为您从 中取回一个字符charAt()
,而不是一个数字。
推荐阅读
- go - 如何仅将一个文件部署到谷歌应用引擎?
- javascript - 如何使用 Jenkins 在 CI 中的 Cypres 仪表板中填充作者、分支、提交、消息?
- angular - 路由器不工作当我需要打开另一个页面时
- java - 如何在 Android Studio 中延迟 getOutputStream().write()?
- python - Plotly.GO(图形对象)和动画
- regex - 正则表达式:匹配“开始”和“结束”,除非包含“否”
- javascript - 如何根据 Google 表格上的列自动在 Google 表单中添加问题?
- flutter - 为什么我需要多次运行带有 if 语句的函数才能到达其他语句?
- python - 获取每小时数据
- javascript - FormControl 验证器始终无效