转换二进制数组转换为十进制 [英] Convert binary to decimal with an array
本文介绍了转换二进制数组转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试着做一个二进制字符串为十进制。如果输入-1它将终止。我坚持使用数组。有人建议使用方法:公共静态INT binaryToDecimal(字符串binaryString)。但林不知道该怎么做。这是我有:
Im trying to make a binary string into a decimal. It will terminate if -1 is entered. I am stuck with using an array. It was suggested to use: public static int binaryToDecimal (String binaryString) . But Im not sure how to do that. This is what I have:
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (inString != "-1") {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = 0, decimal = 0; i < binaryLength; i++) {
decimal = decimal * 2 + (inString[i] - 0);
System.out.print(decimal);
}
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
它说,有与阵列汇编问题。谢谢!
It says there is a compilation problem with the array. Thank you!
推荐答案
您可以通过使用简化code 的Integer.parseInt()
:
You can simplify the code by using Integer.parseInt()
:
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
String inString;
while (true) {
System.out.println("Enter a binary number: ");
inString = input.nextLine();
if (inString.equals("-1"))
break;
System.out.println(Integer.parseInt(inString, 2));
}
System.out.println("All set !");
}
这篇关于转换二进制数组转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文