(java)将十进制数转换为二进制数,而不使用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'
  • 进行比较
  • 如果角色实际上是1:注意位置,将2提高到下一个幂,并将其添加到运行总数

代码如下:

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

此程序将十进制转换为二进制数在java中不使用任何内置的方法,如toBinaryString();

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Binary {
public static void main(String args[]) throws Exception
{
Rstring r=new Rstring();
BufferedReader br=new BufferedReader(new 
InputStreamReader(System.in));
String input=br.readLine();
int number=Integer.parseInt(input);
boolean stop=false;
String result="";
int rem=0;
while(stop==false)
{
if (number==1)
{
rem=1;
result+=Integer.toString(rem);
r.sprint(result);
System.exit(1);
}
else if(number==0)
{
rem=0;
result+=Integer.toString(rem);
r.sprint(result);
System.exit(1);
}
else
{
rem=number%2;
number=number/2;
result+=Integer.toString(rem);
}
}

}
}
class Rstring
{
public void sprint(String input)
{
for(int i=input.length()-1;i>=0;i--)
{
System.out.print(input.charAt(i));
}
System.out.print("n");
}
}

最新更新