Java daily practice (2)

JAVA - Coding exercises:

1. Create a  carName variable named and  Volvo assign the value to it.

             =       ;

Answer


String carName = "Volvo";

2. Create a  maxSpeed variable named and  120 assign the value to it.

          =   ;

Answer


int maxSpeed= 120;

Question 1

Question: There are 5 people sitting together. How old is the fifth person? He said he was 2 years older than the 4th person. When I asked the 4th person how old he was, he said he was 2 years older than the 3rd person. I asked the third person and he said he was two years older than the second person. Asked the second person and said he was two years older than the first person. Finally I asked the first person and he said he was 10 years old. How old is the fifth person?

/**
 * 【程序23】
 * 题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
 */
public class Subject23 {
    public static void main(String[] args) {
        int ageNum = getAge(5);
        System.out.println("第五个人的年龄:"+ageNum);
    }

    /**
     * 获取年龄
     * @param p0
     * @return
     */
    private static int getAge(int p0) {
        if(p0 == 1){
            return 10;
        }else{
            return getAge(p0-1)+2;
        }
    }
}

operation result:

Question 2 

Topic: Given a positive integer with no more than 5 digits, the requirements are: 1. Find out how many digits it has, and 2. Print out the digits in reverse order. 

/**
 * 【程序24】
 * 题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
 */
public class Subject24 {

    public static void main(String[] args) {
        System.out.println("请输入需要分析的正整数:");
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        analysisInt(num);
    }

    /**
     * 分析正整数
     * @param num
     */
    private static void analysisInt(int num) {
        String tmpStr = String.valueOf(num);
        char[] arrStr =tmpStr.toCharArray();
        System.out.println("该正整数是"+arrStr.length+"位数。");
        System.out.println("倒序打印为:");
        for (int i = arrStr.length-1; i >= 0; i--) {
            System.out.print(arrStr[i]+" ");
        }
    }
}

operation result:

Guess you like

Origin blog.csdn.net/m0_69824302/article/details/132520881