简体   繁体   English

二进制到十进制-Java

[英]Binary to Decimal - java

I want to write a program which receive a string value and print the decimal number. 我想编写一个接收字符串值并打印十进制数字的程序。

In addition, if the string value is not 1 or 0, I need to print a message. 另外,如果字符串值不是1或0,则需要打印一条消息。

I wrote this code but it is always getting inside the if command. 我写了这段代码,但是它始终在if命令中。

I Would appreciate your support! 多谢您的支持!

Thank you 谢谢

import java.util.Random; 
public class Decimal {

    public static void main(String[] args) {
        String input = (args[0]);
        int sum = 0;
        for (int i = 0; i <= input.length(); i++) {
            if (!(input.charAt(i) == '0') || (input.charAt(i) == '1')) {
                System.out.println("wrong string");
                break;
            }
            char a = input.charAt(i);
            if (a == '1') {
                sum |= 0x01;
            }
            sum <<= 1;
            sum >>= 1;
            System.out.println(sum);
        }
    }
}

The ! ! (not) operator of the if statement only applies to the first part: (不是) if语句的运算符仅适用于第一部分:

if ( ! (input.charAt(i) == '0')
     ||
     (input.charAt(i) == '1')
   ) {

So that is the same as: 因此与以下内容相同:

if ((input.charAt(i) != '0') || (input.charAt(i) == '1')) {

When you actually meant to do: 当您实际上打算这样做时:

if (input.charAt(i) != '0' && input.charAt(i) != '1') {

It's a good thing though, because once that works, you're going to get an IndexOutOfBoundsException when i == input.length() . 不过这是一件好事,因为一旦i == input.length()i == input.length()时,您将获得IndexOutOfBoundsException Change the loop to: 将循环更改为:

for (int i = 0; i < input.length(); i++) {

And for performance, move variable a up and use it in that first if statement. 而对于性能,移动变量a起来,在第一次使用它if语句。 Rename to c or ch is more descriptive/common. 重命名为cch更具描述性/通用性。

Doing both sum <<= 1 and sum >>= 1 leaves you where you started. sum <<= 1sum >>= 1留在起点。 Is that what you wanted? 那是你想要的吗? You should also do the left-shift before setting the right-most bit. 您还应该设置最右边的位之前先进行左移。

Applying all that, I believe you meant to do this: 应用所有这些,我相信您打算这样做:

String input = args[0];
int sum = 0;
for (int i = 0; i < input.length(); i++) {
    char c = input.charAt(i);
    if (c != '0' && c != '1') {
        System.out.println("wrong string");
        break;
    }
    sum <<= 1;
    if (c == '1')
        sum |= 1;
}
System.out.println(sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM