[英](java) convert a decimal number to binary without using parseint
我是java新手,我正在學習如何從二進制轉換為十進制,反之亦然。 在二進制轉十進制的情況下,我發現我可以使用 parseint,但是我看到了其他沒有使用它的方法,所以我嘗試將它們實現到我的代碼中,但它對我不起作用,我得到了難住了。
我如何能夠使用不同的方法來計算二進制到十進制並將其實現到我的代碼中?
這是我的代碼:
import java.util.Scanner;
class BinaryToDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String binaryString;
char choice;
String nextLine = "Empty";
int i = 0;
choice = 'Y';
try {
do {
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
//Find the string count
int count = binaryString.length();
for (int j = 0; j< count; j++)
{
if (binaryString.charAt(j) != '1' && binaryString.charAt(j) != '0')
{
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
count = binaryString.length();
j=0;
}
}
i = Integer.parseInt(binaryString);
if (i>0)
System.out.println("The decimal number is: " + Integer.parseInt(binaryString, 2));
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.next();
if(ln.length()==1){
choice = ln.charAt(0);
}
else{
choice = 'N';
}
if (sc.hasNextLine()) {
nextLine = sc.nextLine();
}
} while (choice == 'Y');
} catch (NumberFormatException nfe) {
System.out.println("Invalid input");
}
}
}
二進制數學涉及加 1 和乘以 2。我會使用正則表達式來測試輸入是否有效。 當用戶在提示繼續時給出除y
之外的答案時,我會使用無限循環並中斷。 把它放在一起,給出了一個簡化的
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a binary number: ");
String binaryString = sc.nextLine();
// An int value consists of up to 32 0 and 1s.
if (!binaryString.matches("[01]+") || binaryString.length() > 32) {
continue;
}
int v = 0;
for (int i = 0; i < binaryString.length(); i++) {
v *= 2;
if (binaryString.charAt(i) == '1') {
v++;
}
}
System.out.println("The decimal number is: " + v);
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.nextLine();
if (!ln.equalsIgnoreCase("Y")) {
break;
}
}
看起來你錯過了你錯過了我使用的默認值為 2 的基數。試試這個,讓我知道會發生什么
i = Integer.parseInt(binaryString,2);
可能有更好的方法來做到這一點,但是這是我想出的解決方案。 我考慮到該數字既可以是正數也可以是負數,並為這些情況添加了檢查。 我還確保在輸入無效二進制數時添加例外。
public static int numberFromBinary(String binaryNumber) {
char[] array = binaryNumber.toCharArray();
boolean isNegative = false;
int result = 0;
if (array.length > 32) {
throw new NumberFormatException("An integer cannot be more than 32 bits long.");
}
if (array.length == 32) {
isNegative = array[0] == '1';
if (isNegative) {
result -= 1;
}
}
for (int i = 0; i < array.length && i != 31; i++) {
int worth = (int) Math.pow(2, i);
if (array[array.length - 1] != '1' && array[array.length - 1] != '0') {
throw new NumberFormatException("Binary bits can only be a '1' or a '0'.");
}
if (isNegative) {
if (array[array.length - 1] == '0') {
result -= worth;
}
} else {
if (array[array.length - 1] == '1') {
result += worth;
}
}
}
return result;
}
這是將二進制數的字符串表示形式轉換為十進制數的解決方案,無需使用 Integer.parseInt()。 這是基於您的原始問題文本:
我如何能夠使用不同的方法來計算二進制到十進制並將其實現到我的代碼中?
還有您添加的評論:
我也不想使用 parseint
如果你取一個二進制數並從右到左計算,每個數字都是 2 的遞增冪。
0001 = 2^0 = 1
0010 = 2^1 = 2
0100 = 2^2 = 4
1000 = 2^3 = 8
您可以遵循相同的模式:檢查二進制字符串輸入的每個字符位置,然后將 2 提高到某個冪,以獲得該位表示的十進制值被設置為 1。下面是一段簡單的代碼:
'1'
進行比較這是代碼:
System.out.print("enter a binary number: ");
String binaryInput = new Scanner(System.in).next();
int decimalResult = 0;
int position = 0;
for (int i = binaryInput.length() - 1; i >= 0; i--) {
if (binaryInput.charAt(i) == '1') {
decimalResult += Math.pow(2, position);
}
position++;
}
System.out.println(binaryInput + " --> " + decimalResult);
還有一些示例運行:
enter a binary number: 1111
1111 --> 15
enter a binary number: 101010101
101010101 --> 341
enter a binary number: 100000000000
100000000000 --> 2048
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.