【JavaSE】20道简单编程练习题及源码解答

【内容简介】本文我们使用 Java 语言解决20道简单的编程练习题。通过这次练习,相信可以帮助 Java 初学者巩固这门编程语言的部分基础语法,锻炼自身的编码能力。

【程序1】
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....

import java.util.Scanner;

public class Question1 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int temp, num = 1, finalNum = 1;

        int month = input.nextInt();

        if(month >= 3){
            for(int i = 0; i <= month - 3; i++) {
                temp = finalNum;
                finalNum += num;
                num = temp;
            }
        }

        System.out.println("sum is " + finalNum);
    }
}

【程序2】
题目:判断101-200之间有多少个素数,并输出所有素数。
程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,
则表明此数不是素数,反之是素数。

public class Question2 {
    public static void main(String[] args) {
        // Store prime numbers
        int[] primes = new int[100];

        int num = 0;

        boolean primeOrNot = true;
        // All primes are odd
        for(int i = 101; i < 200; i+=2) {
            for(int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    primeOrNot = false;
                    break;
                }
            }

            if(primeOrNot) {
                primes[num] = i;
                num++;
            }

            primeOrNot = true;
        }

        System.out.println("The number of primes is " + num);
        for(int prime:primes) {
            if(prime != 0) {
                System.out.println(prime);
            }
        }
    }
}

【程序3】
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

import static java.lang.Math.pow;

public class Question3 {
    public static void main(String[] args) {
        for(int num = 100; num < 1000; num++) {
            // Determine whether it is a Narcissistic Number.
            if(pow(num % 10,3) + pow(num / 10 % 10,3) + pow(num / 100,3) == num) {
                System.out.printf("%d ",num);
            }
        }
    }
}

【程序4】
题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数 i,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n > i,但n能被 i 整除,则应打印出 i 的值,并用n除以 i 的商,作为新的正整数 n, 重复执行第一步。
(3)如果n不能被 i 整除,则用i+1作为 i 的值,重复执行第一步。

import java.util.Scanner;

public class Question4 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int number = input.nextInt();

        System.out.print(number + " = ");
        printResult(number);
    }
    static void printResult(int n) {
        if(isPrimeNot(n)) {
            System.out.print(n);
        }
        else {
            for(int i = 2; i < n; i++) {
                if(n % i == 0) {
                    // Use recursion
                    System.out.print(i + " * ");
                    printResult(n / i);
                    return;
                }
            }
        }
    }
    static boolean isPrimeNot(int n) {
        for(int i = 2; i <= Math.sqrt(n); i++) {
            if(n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

【程序5】
题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
程序分析:(a>b)?a:b这是条件运算符的基本例子。

import java.util.Scanner;

public class Question5 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int grade = input.nextInt();

        System.out.println(grade >= 90 ? "A" : grade >= 60 ? "B" : "C");
    }
}

【程序6】
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
程序分析:利用辗除法。

import java.util.Scanner;

public class Question6 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int m = input.nextInt();
        int n = input.nextInt();

        System.out.println(m + "," + n + "'s gcd is " + (m > n ? gcd(m,n) : gcd(n, m)));
        System.out.println(m + "," + n + "'s lcm is " + m * n / (m > n ? gcd(m,n) : gcd(n, m)));
    }
    static int gcd(int x, int y) {
        int temp;
        if(x % y == 0) {
            return y;
        }
        else {
            temp = y;
            y = x % y;
            x = temp;
            return gcd(x, y);
        }
    }
}

【程序7】
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用for语句,条件为输入的字符不为'\n'.

import java.util.Scanner;

public class Question7 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String sentence = input.nextLine();

        int[] num = new int[4];
        for(int i = 0; i < sentence.length(); i++) {
            if(Character.toString(sentence.charAt(i)).equals("\n")) {
                break;
            }
            else if(Character.isLetter(sentence.charAt(i))) {
                num[0]++;
            }
            else if(Character.isDigit(sentence.charAt(i))) {
                num[1]++;
            }
            else if(Character.toString(sentence.charAt(i)).equals(" ")) {
                num[2]++;
            }
            else {
                num[3]++;
            }
        }

        System.out.println("The number of letters is " + num[0] + "\n" +
                "The number of numbers is " + num[1] + "\n" +
                "The number of space is " + num[2] + "\n" +
                "The number of other characters is " + num[3]);
    }
}

【程序8】
题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
程序分析:关键是计算出每一项的值。

import java.util.Scanner;

public class Question8 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int num = input.nextInt();
        int number = input.nextInt();

        int result = 0;
        for(int i = 0; i < num; i++) {
            result += (int) (number * Math.pow(10,i) * (num - i));
        }
        System.out.println(result);
    }
}

【程序9】
题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程 找出1000以内的所有完数。

public class Question9 {
    public static void main(String[] args) {
        for(int i = 1; i <= 1000; i++) {
            int sumFactor = 0;
            for(int j = 1; j < i; j++) {
                if(i % j == 0) sumFactor += j;
            }
            if(sumFactor == i) System.out.println(i);
        }
    }
}

【程序10】
题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?

public class Question10 {
    public static void main(String[] args) {
        double high = 100 * Math.pow(0.5,10);
        System.out.println("The height of 10 is " + high);

        double sum = 100;
        for(int i = 0; i < 9; i++) {
            sum += 2 * 100 * Math.pow(0.5, i + 1);
        }
        System.out.println("The sum of height is " + sum);
    }
}

【程序11】
题目:用1、2、3、4,能组成多少个互不相同且无重复数字的三位数?都是多少?
程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去掉不满足条件的排列。

public class Question11 {
    public static void main(String[] args) {
        int count = 0;
        System.out.println("the number of satisfied three-digit number: ");
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= 4; j++) {
                if (j != i) {
                    for (int k = 1; k <= 4; k++) {
                        if (k != i && k != j) {
                            count++;
                            System.out.println(i * 100 + j * 10 + k);
                        }
                    }
                }
            }
        }
        System.out.println("the sum is " + count);
    }
}

【程序12】
题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润,求应发放奖金总数?
程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。

import java.util.Scanner;

public class Question12 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        long profit = input.nextLong();
        long bonus = 0;

        if (profit <= 100000) {
            bonus = (long) (profit * 0.1);
        } else if (profit <= 200000) {
            bonus = (long) (100000 * 0.1 + (profit - 100000) * 0.075);
        } else if (profit <= 400000) {
            bonus = (long) (100000 * 0.1 + 100000 * 0.075 + (profit - 200000) * 0.005);
        } else if (profit <= 600000) {
            bonus = (long) (100000 * 0.1 + 100000 * 0.075 + 200000 * 0.005 + (profit - 400000)
                    * 0.003);
        } else if (profit <= 1000000) {
            bonus = (long) (100000 * 0.1 + 100000 * 0.075 + 200000 * 0.005 + 200000 * 0.003
                    + (profit - 600000) * 0.001);
        }

        System.out.println(bonus);
    }
}

【程序13】
题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
程序分析:在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后的结果满足条件,则求得该数。

public class Question13 {
    public static void main(String[] args) {
        int number = 1;
        while(!(isPerfectNot(number + 100) && isPerfectNot(number + 168))) {
            number += 1;
        }
        System.out.println(number);
    }

    static boolean isPerfectNot(int n) {
        return (int) (Math.sqrt(n)) * (int) (Math.sqrt(n)) == n;
    }
}

【程序14】
题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。

public class Question14 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int year = input.nextInt();
        int month = input.nextInt();
        int day = input.nextInt();

        int allDay = 0;
        int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};

        if (month == 1) {
            allDay = day;
        }
        else if (month == 2) {
            allDay = months[0] + day;
        }
        else {
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                months[1] = 29;
            }
            for (int i = 0; i < month - 1; i++) {
                allDay += months[i];
            }
            allDay += day;
        }

        System.out.println(allDay);
    }
}

【程序15】
题目:输入三个整数x,y,z,请把这三个数由小到大输出。
程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。

import java.util.Scanner;
public class Question15 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int x = input.nextInt();
        int y = input.nextInt();
        int z = input.nextInt();

        int temp;

        if (x > y) {
            temp = x;
            x = y;
            y = temp;
        }
        if (x > z) {
            temp = x;
            x = z;
            z = temp;
        }
        if (y > z) {
            temp = y;
            y = z;
            z = temp;
        }

        System.out.printf("%d < %d < %d", x, y, z);
    }
}

【程序16】
题目:输入三个数a,b,c,求解一元二次方程 ax^2+b^x+c=0。

import java.util.Scanner;
public class Question16 {
    public static void main(String[] args) {
        // Solve a system of linear equations of two unknowns

        // Create a Scanner object
        Scanner input = new Scanner(System.in);

        // Create parameter
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();

        double delta = b * b - 4 * a * c;
        if (delta < 0) {
            System.out.println("parameter wrong");
        }
        else {
            double Solution1 = (-b + Math.sqrt(delta)) / (2*a);
            double Solution2 = (-b - Math.sqrt(delta)) / (2*a);
            System.out.print("The result is: "); // The end of line have not
            System.out.println("x = " + Solution1 + " or " + Solution2);
        }
    }
}

【程序17】
题目:输出一张杨辉三角图,共10行。

public class Question17 {
    public static void main (String[] args) {
        final int MAX = 10;

        int[][] odds = new int[MAX + 1][];
        for (int i = 0; i <= MAX; i++) {
            odds[i] = new int[i + 1];
        }

        for (int i = 0; i < odds.length; i++) {
            for (int j = 0; j < odds[i].length; j++) {
                int lotteryOdds = 1;
                for (int k = 1; k <= j; k++) {
                    lotteryOdds = lotteryOdds * (i - k + 1) / k;
                }
                odds[i][j] = lotteryOdds;
            }
        }

        for (int[] row : odds) {
            for (int odd : row) {
                System.out.printf("%4d",odd);
            }
            System.out.println();
        }
    }
}

【程序18】
题目:
实现随机产生一个5位的验证码,每位可能是数字、大写字母、小写字母。

import java.util.Random;

public class Question18 {
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder();

        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            char element = generateRandomLetterOrDigit(random);
            stringBuilder.append(element);
        }

        String ranCode = stringBuilder.toString();

        System.out.println(ranCode);
    }

    static char generateRandomLetterOrDigit(Random random) {
        int type = random.nextInt(3);
        int value = switch (type) {
            case 0 -> // generate big letter
                    random.nextInt(26) + 'A';
            case 1 -> // generate small letter
                    random.nextInt(26) + 'a';
            default -> // generate digit
                    random.nextInt(10) + '0';
        };
        return (char) value;
    }
}

【程序19】
题目:输入一个字符串,再输入一个短字符串,判断短字符串在长字符串中的出现次数。

import java.util.Scanner;

public class Question19 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String string = input.next();
        String testString = input.next();

        int number = 0;

        boolean state = true;
        for (int i = 0; i < string.length(); i++) {
            for (int j = 0; j < testString.length(); j++) {
                if (string.charAt(i+j) != testString.charAt(j)) {
                    state = false;
                    break;
                }
            }
            if (state) number++;
            state = true;
        }

        System.out.println(number);
    }
}

【程序20】
题目:
一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。

import java.util.Scanner;

public class Question20 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // int number=scanner.next();
        String numberStr = input.next();
        // Convert a string to a character array.
        char[] numberStrArray = numberStr.toCharArray();

        int n = numberStrArray.length;

        System.out.println("the number is "+n+" digit number");
        for(int i = 0; i < n; i++){
            System.out.print(numberStrArray[n - i - 1]);
        }
    }
}
  • 17
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值