java basic exercises

Posted by Devsense on Mon, 09 Sep 2019 14:46:13 +0200

1 Variables, Operators and Type Conversions:
1.1 Input a student's score manually, add 20% of the current score to the score once, and output the result after the score is added.

        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a number.");
        int num = scan.nextInt();
        num += num * 0.2;
        System.out.println(num);

1.2 Shopping malls hold store celebrations with a few discounts.
Input the amount of consumption manually, then enter the discount and calculate the discount price.

        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the amount of consumption");
        int num = scan.nextInt();
        System.out.println("Please enter the discount.");
        int dis = scan.nextInt();
        int price = 0;// Cumulative variable
        price = num * dis / 10;
        System.out.println("Discount price:" + price);

1.3 Input a 4 digit number manually to find the sum of the digits.

        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a four-digit number");
        int shu = scan.nextInt();
        int a = shu / 1 % 10;
        int b = shu / 10 % 10;
        int c = shu / 100 % 10;
        int d = shu / 1000 % 10;
        System.out.println(a + b + c + d);

2 branching structure:
2.1 Consumer rebate activities in shopping malls, input the amount of customer consumption manually.
If the amount still reaches 1000 yuan after 8% discount, the user will get a 200 yuan voucher (not considering multiple vouchers).

        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the amount of consumption");
        int num = scan.nextInt();

        double dis = num * 0.8;// Discounted price
        if (dis > 1000) {
            dis = dis - 200;// 200 Vouchers of the Yuan Dynasty
        }
        System.out.println(dis);

 

2.2 User input a year, if leap year output is leap year
(Years divisible by four, not by 100, or by 400)

        Scanner input = new Scanner(System.in);
        System.out.println("Input year");
        int year = input.nextInt();
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            System.out.println("It's a leap year.");
        } else {
            System.out.println("Not a leap year");
        }

 

2.3 Manually enter an integer membership number.
If the user enters a four-digit number,
The output login was successful.
If the user does not enter a four-digit number,
Output "incorrect membership number you entered"

        Scanner input = new Scanner(System.in);
        System.out.println("Please enter the integral membership number.");
        int num = input.nextInt();
        int i = 0;// Number of digits initialized
        while (num != 0) {
            num = num / 10;// Divided by 10 i++;
        } // Finally, this i That's the number of digits in a number.
        if (i != 4) {
            System.out.println("The membership number you entered is incorrect.");
        } else {
            System.out.println("Successful login!");
        }

 

2.4 Manually input the values of variables a, b and c.
Require numerical exchange,
Increase the number of inputs from small to large
Sort into a,b,c, and output

        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter the first integer:");
        int a = scanner.nextInt();
        System.out.print("Enter the second integer:");
        int b = scanner.nextInt();
        System.out.print("Enter the third integer:");
        int c = scanner.nextInt();

        int x = 0;
        if (a > b) {
            x = a;
            a = b;
            b = x;
        }
        if (a > c) {
            x = a;
            a = c;
            c = x;
        }
        if (b > c) {
            x = b;
            b = c;
            c = x;
        }
        System.out.println(a + "," + b + "," + c);

 

3-branch structure
3.1 Shopping malls are discounted on the basis of membership points.
9% discount within 2000 points.
8% discount within 4000 points
A discount of 7.5% for less than 8000 points.
Over 8000 points, 7% discount.
Using if-else-if structure, the purchase amount and integral can be input manually, and the payment amount can be calculated.

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the purchase amount.");
        double shop = sc.nextDouble();
        System.out.println("Please enter the integral.");
        int fen = sc.nextInt();
        if (fen < 2000) {
            shop *= 0.9;
            System.out.println("Current consumption" + shop + "element");
        } else if (fen >= 2000 && fen <= 4000) {
            shop *= 0.8;
            System.out.println("Current consumption" + shop + "element");
        } else if (fen <= 8000 && fen > 4000) {
            shop *= 0.75;
            System.out.println("Current consumption" + shop + "element");
        } else if (fen > 8000) {
            shop *= 0.7;
            System.out.println("Current consumption" + shop + "element");
        } else {
            System.out.println("Sorry, there is no discount.");
        }

 

3.2 Ticket prices are charged according to off-season peak season, first class and economy class.
Input the original fare, month and first class or economy class.
During the peak season (May-October), the first class fare will be 9% discount and the economy class will be 85% discount.
In the off-season (November to April of next year), the first class fare is 7% discount and the economy class is 65% discount.
Final Output Ticket Price

        Scanner s = new Scanner(System.in);
        System.out.println("Please enter the original ticket price.");
        int piao = s.nextInt();
        System.out.println("Please enter month");
        int yue = s.nextInt();
        System.out.println("Please choose:1.First-class" + "2.Economics");
        int l = s.nextInt();
        if (yue >= 5 && yue <= 10) {// Busy season
            if (l == 1) {
                piao *= 0.9;
            } else {
                piao *= 0.85;
            }

        } else {// Low Season
            if (l == 1) {
                piao *= 0.7;
            } else {
                piao *= 0.65;
            }

        }
        System.out.println(piao);

 

3.3 Choose a shape (1 rectangle, 2 square, 3 triangle, 4 circle)
Users are allowed to enter different information according to different choices.
A rectangle has length and width.
Squares have edges and lengths.
A triangle has a bottom and a height.
The circle has a radius.
Calculate the area of the output specified shape

        Scanner scan=new Scanner(System.in);
        System.out.println("1 Rectangle, 2 square, 3 triangle, 4 circle");
        int num=scan.nextInt();
        switch(num) {
        case 1:
            System.out.println("Please enter a rectangle");
            int l=scan.nextInt();
            System.out.println("Please enter the width of the rectangle");
            int w=scan.nextInt();
            int fs=l*w;
            System.out.println("The area of a rectangle is:"+fs);
            break;
        case 2:
            System.out.println("Please enter the square side length.");
            int z=scan.nextInt();
            System.out.println("The square area is:"+z*z);
            break;
        case 3:
            System.out.println("Please enter the bottom length of the triangle.");
            int d=scan.nextInt();
            System.out.println("Please enter the height of the triangle");
            int g=scan.nextInt();
            System.out.println("The area of the triangle is:"+d*g/2);
            break;
        case 4:
            System.out.println("Please enter the radius of the circle");
            double r=scan.nextDouble();
            double ys=3.14*r*r;
            System.out.println("The circular area is:"+ys);
            break;
        }

 

3.4 Input year and month, how many days should output this month (using switch structure)

        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the year");
        int year = scan.nextInt();
        System.out.println("Please enter month");
        int month = scan.nextInt();
        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            System.out.println("31 day");
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            System.out.println("30 day");
            break;
        case 2:
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                System.out.println("29 day");
            } else {
                System.out.println("28 day");
            }
        }

 

4 Cyclic Structure (Part I)
4.1 Randomly generates a num between 1 and 100, and the loop lets the user enter the guess number.
If the number entered by the user is larger than the number entered by num prompt,
If the number entered by the user is less than num, the number entered by the user is smaller.
Until the number entered by the user is equal to num, then the total number of guesses is output.

        Scanner scan=new Scanner(System.in);
        Random ran=new Random();
        //Generate Game Answer 1~100
        int num=ran.nextInt(100)+1;
        //System.out.println(num);
        int n=0;//Definition n Initial value
        int i=0;//Define the number of guesses
        while(n!=num) {
            System.out.println("Guess the number, please.");
            n=scan.nextInt();
            if(n>num) {//Judging the result of guessing
                System.out.println("The number of input is large.");
            }else if(n<num) {
                System.out.println("The number of inputs is small");
            }else {
                System.out.println("Congratulations on your guess");
            }
            i++;//Number of guesses plus 1
        }
        System.out.println("All guessed."+i+"second");

 

4.2 Prints out all numbers between 1 and 100 that are not multiples of 7 and do not contain 7, and sums them up.

        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if(i%7 ==0 || i%10 == 7 || i/10 == 7){//Note: 70-79 Easy to miss out
                continue;
            }
            sum += i;
        }
        System.out.println(sum);

 

4.3 Loop input 5 numbers, after the completion of these numbers show whether there is a negative number.

        Scanner scan=new Scanner(System.in);
        System.out.println("Please enter five numbers");
        int flag=0;//Set up a flag
        int i=1;
        while(i<=5) {
            int num=scan.nextInt();
            if(num<0) {
                flag=1;
            }
            i++;
        }
        if(flag==0) {
            System.out.println("No negative number");
        }else {
            System.out.println("Negative number");
        }

 

5 Cyclic Structure (Part 2)
5.1 There is a rich neurosis who deposits money in the bank.
Save 1 yuan on the first day and 50% more on the next day than on the previous day. Complete the following calculation tasks
1) He will deposit more than 10 yuan on the next day.

        double money=1;
        int day=1;
        while(money<10) {
            money*=1.5;
            day++;
            System.out.println("day:"+day+",money:"+money);
        }
        System.out.println(day);


2) How much money did he save after a month (30 days)

double sum=0;
        double mo=1;
        for(int i=1;i<=30;i++) {
            sum+=mo;
            System.out.println("i:"+i+",money:"+mo+",sum:"+sum);
            mo*=1.5;
        }
        System.out.println(sum);

 

 

 

5.2 There is a 400-metre-lap playground where one runs 10000 metres.
Fifty seconds in the first lap and one second slower in each subsequent lap than in the previous one.
According to this rule, how many seconds does it take to run 10000 meters?

        int round=10000/400;
        int sum=0;
        int time=50;
        for(int i=1;i<=round;i++) {
            sum+=time;
            System.out.println("Cycle number:"+i+",time:"+time+",Time spent:"+sum);
            time++;
        }
        System.out.println(sum);

 

5.3 Users enter any integer and find the sum of the digits.

        Scanner scan=new Scanner(System.in);
        System.out.println("Please enter a number.");
        int num=scan.nextInt();
        int sum=0;//Cumulative variable
        while(num>0) {
            //Take the digits out and add them up
            sum+=num%10;
            //Divide the current number by 10,For next reuse
            num=num/10;//num/=10;
        }
        System.out.println(sum);

 

5.4 There is a snail in the well. He climbs 5 meters during the day and falls 3.5 meters at night. The well is 56.7 meters deep.
Calculate how many days it takes a snail to climb out of the bottom of the well

        int day=1;//Days
        double sum=0;//The distance of climbing
        while(true) {
            //Climbing up 5 metres during the day
            sum+=5;
            System.out.println("day:"+day+",sum:"+sum);
            if(sum>=56.7) {//If you climb out of the well
                //Exit the cycle
                break;
            }
            //Loss of 3 at night.5;
            sum-=3.5;
            day++;
        }
        System.out.println(day);

 

6-cycle nesting
6.1 Find the list of internal prime numbers less than 1-1000
PS: A prime is an integer divisible only by 1 and itself

        int i, j;
        for (i = 1; i <= 1000; i++) {
            for (j = 2; j < i; j++) {
                if (i % j == 0)
                    break;
            }

            if (i == j){
                System.out.print(j + " ");
            }

        }

 

7 arrays
7.1 Defines an array int[] nums={8,7,3,9,5,4,1}
Subscripts for the maximum and maximum values in the output array

        int[] nums={8,7,3,9,5,4,1};
        int max = nums[0];//Default first maximum
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > max) {
                max = nums[i];
                index = i;
            }
        }
        System.out.println("Maximum number: "+max+" Subscription: "+index);

 

7.2 Randomly generate 10 0-9 random integers from an array of integers of length 10 to accomplish the following tasks
1) ascending and descending output
2) Output summation, average

        Random ran = new Random();
        int[] num = new int[10];
        for (int i = 0; i < num.length; i++) {
            num[i] = ran.nextInt(10);
        }
        Arrays.sort(num);
        for (int i = 0; i < num.length; i++) {
            System.out.print(num[i] + " ");
        }
        System.out.println("------Ascending order------");
        for (int i = num.length - 1; i >= 0; i--) {
            System.out.print(num[i] + " ");
        }
        System.out.println("------Descending order------");

        // The sum
        int sum = 0;
        for (int i = 0; i < num.length; i++) {
            sum = num[i] + sum;
        }
        System.out.println("The sum:" + sum);

        // Average
        int sum2 = 0;
        for (int i = 0; i < num.length; i++) {
            sum2 = num[i] + sum2;
        }
        System.out.println("Average:" + sum2 / num.length);

 

Random Generation of 5 1-10 Random Integers in an Array of Integers of 5 Length in 7.3 Direction
There are no duplicates in the number required to be generated

        int[] nums = new int[5];
        Random ran = new Random();
        
        for (int i = 0; i < nums.length; i++) {
            nums[i] = ran.nextInt(10) + 1;
            
            for (int j = 0; j < i; j++) {
                while (nums[i] == nums[j]) {//If repeated, go back and regenerate the random number
                    i--;
                }
            }
        }
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }

 

7.4 (optional) Randomly generate 10 0-9 random integers from an integer array of length 10 to accomplish the following tasks
1) Statistics on how many times each figure appears
2) Numbers with the largest number of output occurrences
3) The smallest number of numbers that appear only once in the output

        Random r = new Random();
        // 1. Declare the source array, containing 10 0-9 Random numbers between
        int[] src = new int[10];
        // 2. Declare an array of tags that store 0-9,10 Numbers
        int[] flag = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        // 3. Declare a number in an array of statistical tags at the source
        // Number of arrays
        int[] count = new int[flag.length];
        // 4. Assign 0 to the source array-9 Random numbers between
        for (int i = 0; i < src.length; i++) {
            src[i] = r.nextInt(10);
        }
        // 5. Each element in the statistical tag array is in the source array
        // How many will you give? count Array assignment
        for (int i = 0; i < flag.length; i++) {
            for (int j = 0; j < src.length; j++) {
                // If the number in the tag array is in the source array, count+1
                if (flag[i] == src[j]) {
                    count[i]++;
                }
            }
        }
        // 6. output src and count Data
        System.out.println("The randomly generated data are as follows:");
        System.out.println(Arrays.toString(src));
        // System.out.println(Arrays.toString(count));

        // a.Statistics on the number of occurrences of each figure
        // If count If the value of an element is greater than 0, its subscript and value are output.
        for (int i = 0; i < count.length; i++) {
            if (count[i] > 0) {
                System.out.println("number" + i + "Appear" + count[i] + "second");
            }
        }

        // b.Output Number of Repeated Numbers
        // Suppose the first statistic is the maximum one.
        int max = count[0];
        int index = 0;
        for (int i = 0; i < count.length; i++) {
            if (count[i] > max) {
                max = count[i];
                index = i;
            }
        }
        System.out.println("The number that appears most frequently is" + index);

        // c. The smallest number of numbers that appear only once in the output
        for (int i = 0; i < count.length; i++) {
            if (count[i] == 1) {
                System.out.println("The smallest number of occurrences is" + i);
                break;
            }
        }

 

 

 

good luck!

Topics: Java less