好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java基础题新手练习(二)

数字9 出现的次数

编写程序数一下 1到 100 的所有整数中出现多少个数字9

 

 

源码

public static int Getnum (){ int count = 0 ; for ( int i = 1 ; i <= 100 ; i ++){ if ( i % 10 == 9 ) { count ++; } if ( i / 10 == 9 ) { count ++; } } return count ; }

运行结果:

输出闰年

输出 1000 - 2000 之间所有的闰年

源码

public static void SoutLeapyear (){ for ( int year = 1000 ; year <= 2000 ; year ++) if ( year % 100 != 0 && year % 4 == 0 || year % 400 == 0 ){ System . out . println ( year + "是闰年" ); }   }

运行结果:

打印素数

打印 1 - 100 之间所有的素数

源码

public static void PrintPrimeNum (){ for ( int i = 2 ; i < 100 ; i ++) { int j ; for ( j = 2 ; j < ( int ) ( Math . sqrt ( i ) + 1 ); j ++) { if ( i % j == 0 ) { break ; } } if ( j > ( int ) Math . sqrt ( i )) { System . out . print ( i + " " ); } }   }

运行结果:

判定素数

给定一个数字,判定一个数字是否是素数

源码

public static void PrintPrimeNum (){ for ( int i = 2 ; i < 100 ; i ++) { int j ; for ( j = 2 ; j < ( int ) ( Math . sqrt ( i ) + 1 ); j ++) { if ( i % j == 0 ) { break ; } } if ( j > ( int ) Math . sqrt ( i )) { System . out . print ( i + " " ); } }   }

运行结果:

年龄打印

根据输入的年龄, 来打印出当前年龄的人是少年(低于18), 青年(19-28), 中年(29-55), 老年(56以上)

源码

public static void JudgeAge (){ Scanner scanner = new Scanner ( System . in ); int age = scanner . nextInt (); if ( age < 18 ) System . out . println ( "是少年" ); else if ( age >= 19 && age <= 29 ) System . out . println ( "是青年" ); else if ( age >= 20 && age <= 55 ) System . out . println ( "是中年" ); else if ( age >= 56 && age <= 100 ) System . out . println ( "是老年" ); elseSystem . out . println ( "输入有误" ); }

运行结果:

打印 X 图形

KiKi学习了循环,BoBo老师给他出了一系列打印图案的练习,该任务是打印用[*]组成的X形图案。

源码

public static void PrintX (){ Scanner sc = new Scanner ( System . in ); int num = sc . nextInt (); for ( int i = 1 ; i <= num ; i ++){ for ( int j = 1 ; j <= num ; j ++){ if (( i == j ) || ( i + j == num + 1 )) System . out . print ( "x" ); else { System . out . print ( " " ); } } System . out . println (); } }

运行结果:

猜数字游戏

完成猜数字游戏 ,用户输入数字,判断该数字是大于,小于,还是等于随机生成的数字,等于的时候退出程序。

源码

public static void guessNumber (){ Scanner scanner = new Scanner ( System . in ); Random random = new Random (); //用来生成随机数 int randNum = random . nextInt ( 100 ); while ( true ) { System . out . println ( "请输入你要猜的数字:" ); int num = scanner . nextInt (); if ( num < randNum ) { System . out . println ( "小了" ); } else if ( num == randNum ) { System . out . println ( "猜对了" ); break ; } else { System . out . println ( "大了!" ); } } }

运行结果:

总结

本篇java基础练习题就到这里了,希望对你有所帮助,也希望您能够多多关注我们的更多内容!

原文链接:https://blog.csdn.net/qq_45859087/article/details/115470432

查看更多关于Java基础题新手练习(二)的详细内容...

  阅读:13次