(1)通过合理的判断,符合正常思路
import java.util.Scanner;
public class test4 {
public static void main(String[] args) {
/*
从键盘输入某个十进制整数数,转换成对应的二进制整数并输出。
*/
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个十进制的整数:");
int number = sc.nextInt();
int tmpNumber = number;
//定义一个变量作为商
int shang = 0;
int yuShu = 0;
String res = "";
do {
shang = number / 2;
yuShu = number % 2;
res = yuShu + res;
number = shang;
} while (shang!=0);
System.out.println(tmpNumber+"的二进制为:"+res);
}
}
(2)直接调用二进制转化方法
import java.util.Scanner;
public class test14 {
public static void main(String[] args) {
//获取用户输入
Scanner sc = new Scanner(System.in);
System.out.println("请随机输入一大于0的十进制整数:");
//检验用户输入的数值是否符合要求
if(sc.hasNextInt()){
int num=sc.nextInt();
if(num>=0){
System.out.print("十进制"+num+"的二进制为:");
String binary = Integer.toBinaryString(num);//直接调用Integer.toBinaryString()方法
System.out.println(binary);
}else{
System.out.println("您输入的数值有误");
}
}else{
System.out.println("您输入的数值有误");
}
}
}
标签:Scanner,二进制,编程,System,int,println,十进制,out
From: https://www.cnblogs.com/k8409/p/18331190