目录
(1)回文数
public class 回文数 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int num=0;
System.out.println("请输入数字:");
int x = sc.nextInt();
int a=x;
while (a%10!=0){
int ge = a%10;
a/=10;
num=num*10+ge;
}
if (x==num){
System.out.println("该数字是回文数!");
}else {
System.out.println("该数字不是回文数!");
}
}
}
(2)求商和余数
public class 求商和余数 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入被除数:");
int a = sc.nextInt();
System.out.println("请输入除数:");
int b = sc.nextInt();
int count=0;
if (a>=0&&b>=0){
while (a>=b){
a-=b;
count++;
}
System.out.println("商是:"+count);
System.out.println("余数是:"+a);
}else {
System.out.println("请输入正整数!");
}
}
}
(3)求平方根
public class 求平方根 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入大于等于2的数字:");
int x= sc.nextInt();
if (x>=2){
for (int i=1;i<=x;i++){
if (i*i==x){
System.out.println("1该数字的平方根是:" +
i);
break;
} else if (i*i>x) {
System.out.println("2该数字的平方根是:" +
(i-1));
break;
}
}
}else {
System.out.println("请输入符合条件的数字!");
}
}
}
(4)求质数
public class 求质数 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个正整数:");
int a = sc.nextInt();
boolean flag=true;
//质数:如果一个数只能被1和本身整除,那么这个数就是质数,否则就是合数
//只有循环完毕,才能够判读这个数是否是质数,若a%i!=0,则有可能未循环完毕就跳出循环。
for (int i=2;i<a;i++){
if (a%i==0){
flag=false;
break;
}
}
if (flag){
System.out.println("这是一个质数!");
}else {
System.out.println("这是一个合数!");
}
}
}
(5)猜数字小游戏
public class 猜数字小游戏 {
//程序自动生成1~100之间的一个随机数字,使用程序猜出这个数字是多少
public static void main(String[] args) {
Random r = new Random();
int number = r.nextInt(100)+1;//0~9 +1 -> 1~100
Scanner sc = new Scanner(System.in);
System.out.println("输入你要猜的数字:");
int count=0;
while (true){
count++;
int a = sc.nextInt();
if (count==6){
System.out.println("菜鸡,你终于猜对了!"); //保底机制
break;
}
if (a>number){
System.out.println("大了");
} else if (a<number) {
System.out.println("小了");
}else {
System.out.println("恭喜你猜对了!");
break;
}
}
}
}