使用Java错误将十进制转换为二进制

时间:2018-06-30 21:31:46

标签: java

我对程序是否正确感到困惑或缺少什么!

我可以从中得到输出。

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter you String: ");
    String bin = sc.nextLine();

    int length = bin.length();
    int j = 0;
    int sum = 0;

    if (length != 0) {
        for (int i = length - 1; i >= 0; i--) {
            if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
                String s = bin.charAt(j) + "";
                sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
                j++;
            } else {
                System.out.println("illegal input.");
            }
        }
        System.out.println(sum);
    } else {
        System.out.println("illegal input.");

    }
}

1 个答案:

答案 0 :(得分:1)

删除此行上的引号:

if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {

应成为

if (bin.charAt(i) == 0 || bin.charAt(i) == 1) {

以下代码可以正常工作:

import java.util.Scanner;

public class test {
public static void main (String args []) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter you String: ");
    String  bin = sc.nextLine();

    int length = bin.length();
    int j = 0;
    int sum = 0;

    if (length != 0) {
        for (int i = length - 1; i >= 0; i--) {
            if (bin.charAt(i) == '0' || bin.charAt(i) == '1') {
                String s = bin.charAt(j) + "";
                sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
                j++;
            } else {
                System.out.println("illegal input.");
            }
        }
        System.out.println(sum);
    } else {
        System.out.println("illegal input.");

    }
}
}