數字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