`
wpf814533631
  • 浏览: 192295 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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;
    }
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics