java 求二进制

闲来无事,写了一个求二进制的类:

import java.util.Scanner;

public class ErJinZhi {
    public static void main(String[] args) {
        boolean want = true;
        while (want) {
            System.out.print("请输入一个整数:");
            Scanner scanner = new Scanner(System.in);
            int index;
            try {
                index = scanner.nextInt();
            } catch (Exception e) {
                System.out.println("输入错误!!!");
                want = true;
                continue;
            }
            System.out.println(index + " 的二进制是 " + erJinZhi(index));
            System.out.print("你想继续吗?(y/n):");
            do {
                String c = scanner.next();
                if (c.equals("n") || c.equals("N")) {
                    want = false;
                    System.out.println("exit !!!");
                    break;
                } else if (c.equals("y") || c.equals("Y")) {
                    want = true;
                    break;
                } else {
                    System.out.print("\n请继续选择(y/n):");
                    continue;
                }
            } while (true);
        }
    }

    private static String erJinZhi(int index) {
        String erjizhi = "";
        while (true) {
            if (index >= 2) {
                int yu = index % 2;
                index = index / 2;
                erjizhi = yu + erjizhi;
                continue;
            } else {
                erjizhi = index + erjizhi;
                break;
            }
        }
        return erjizhi;
    }
}
 

你可能感兴趣的:(java)