它先將鍵盤上輸入的一個字符串轉換成十進制整數,然后打印出這個十進制整數對應的二進制
package com.test.code;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Erjinzhi {
/**
* 它先將鍵盤上輸入的一個字符串轉換成十進制整數,然后打印出這個十進制整數對應的二進制形式。
* @param args
*/
public static void main(String[] args) {
int shang = 0, yu;
boolean flag = false;
System.out.println("請輸入一個數字(最大值為<" + Integer.MAX_VALUE + ")");
InputStream inputStream = System.in;
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
try {
String str = reader.readLine();
char[] ch = new char[str.length()];
str.getChars(0, ch.length, ch, 0);
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(ch[i])) {
System.out.println("有非數字字符");
System.exit(0);
}
}
try {
shang = Integer.parseInt(str);
flag = true;
} catch (Exception ex) {
ex.printStackTrace();
}
//不斷用二除,直到除不開,再把余數倒置
str = "";
if (flag) {
while (shang != 0) {
yu = shang % 2;
shang = shang / 2;
str = yu + str;
}
}
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文由用戶 quanzhong 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!