编辑:由于有人声称这是一个重复的问题,我将陈述我为什么不这样做的立场。
另一个问题是关于将字符串输入转换为整数的问题(答案被认为是正确的)。这与此无关,因为我的案例中的问题是逻辑问题。
另一个问题的解决方案无法解决此问题所带来的问题(找到语法" charAt"错误)。
坦率地说,另一个问题的背景超出了我在Java中的知识范围。
我已经成功创建了一个将二进制数转换为十进制数的程序。
import java.util.Scanner;
public class ProblemThree // to convert binary to decimal
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
int[] number = new int[length];
int[] powerTwo = new int[length];
// To list every digit separately //
for (int n = 0; n <= length - 1; n++)
{
number[n] = (int) (binary / Math.pow(10, n)) % 10;
}
// To set the values in powerTwo to 2 //
for (int n = 0; n <= length - 1; n++)
{
powerTwo[n] = 2;
}
// To update the values in powerTwo //
for (int n = 0; n <= length - 1; n++)
{
if (n == 0)
powerTwo[0] = 1;
else if (n == 1)
powerTwo[1] = 2;
else
powerTwo[n] *= powerTwo[n-1];
}
// To add if current value is 1 //
for (int n = 0; n <= length - 1; n++)
{
if (number[n] == 1)
answer += powerTwo[n];
}
System.out.println(powerTwo[0]); // for testing
System.out.println(number[0]); // for testing
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
看到一些步骤是多余的,我试图简化代码。
import java.util.Scanner;
public class ProblemThreeTestFunction
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
String number = String.valueOf(binary);
for (int n = 0; n <= length - 1; n++)
{
if (number.charAt(n) == 1)
answer += (int)Math.pow(2, n);
}
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
我实际上不知道为什么简化的代码逻辑不起作用。它使用与我原来相同的概念。
先谢谢!
答案 0 :(得分:3)
为什么不使用:
int decimalValue = Integer.parseInt(binary, 2);
但如果您使用此功能,则需要使用scan.nextLine()
而不是scan.nextInt()
。
这只会使用基数10将您的二进制数转换为十进制数,如here所示。
答案 1 :(得分:1)
您需要针对字符'1'
进行测试:
if (number.charAt(n) == '1')
不是您目前正在做的数字1:
if (number.charAt(n) == 1) // WRONG!
此外,由于charAt
从左侧开始计数,而二进制扩展从右侧开始计数,因此您需要颠倒这种意义。变化
Math.pow(2, n)
到
Math.pow(2, length - 1 - n)
答案 2 :(得分:1)
您正在与数字1进行比较,它应该是字符1,即&#39; 1&#39;。
for (int n = 0; n <= length - 1; n++) {
if (number.charAt(n) == '1') {
answer += (int)Math.pow(2, length - n - 1);
}
}
您还需要更正指数部分。