Java基础练习题(4)

215 阅读2分钟

开启掘金成长之旅!这是我参加「掘金日新计划·12月更文挑战」的第三天,点击查看活动详情

题目七:抢红包

需求

一大大V直播抽奖,奖品是现金红包,分别有{2,588,888,1000,10000}五个奖金。请使用代码模拟抽奖,打印出每个奖项,奖项的出现顺序要随机且不重复。

分析

  1. 定义数组表示奖池
  2. 定义新数组用于存储抽奖的结果
  3. 抽奖(使用for循环)
  4. 遍历
import java,util.Random;
public class Test7{
    public static void main(String[] args){
        //1.把奖池里面的所有奖项打乱顺序
        int[] arr = {2588888100010000};
        Random r = new Random();
        for(int i = 0;i< arr.length;i++){
            //获取随机索引
            int randomIndex = r.nextInt(arr.length);
            //拿着i和随机索引randomIndex上的值进行交换
            int temp = arr[i];
            arr[i] = arr[randomIndex];
            arr[randomIndex] = temp;
        }
        //2.遍历奖池,从0索引开始获取每一个奖项
        for(int i = o;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
}    

题目八:阶乘求和

需求

编写一个Java程序在屏幕上输出1!+2!+3!+......+10!的和

分析

  • 给定任意数字n,计算1-n的所有数字阶乘之和:例如:用户输入5,则计算5!+4!+3!+2!+1!
  • 阶乘:factorial
  • 功能:计算任意数字n的1-n的所有阶乘之和;计算结束后可选择是否继续
import java.util.Scanner;
public class Test8{
   public static void main(String[] args){
       Scanner sc = new Scanner(System.in);
       System.out.println("欢迎使用累计阶乘计算器");
       
       while(true){
           System.out.println("请输入一个数字n,用于求1-n的所有数字的阶乘的和。");
           int n = sc.nextInt();
           int sum = 0;
           for(int y = 1;y<= n;y++){
              sum = factorial.factorialcal(y) + sum;
           }   
           System.out.println("1-" + n + "的所有数的阶乘的和为:" + sum);
           System.out.println("计算已经结束,继续计算轻按1,任意健可退出!");
           int quit = sc.nextInt();
           if(quit != 1){
               break;
           }
       }
   }
}

class factorial{
     //该方法用于求任意数字n的阶乘
     public static int factorialcal(int n){
         int sum = 1;
         for(int i = 1;i<=n;i++){
            sum *= i;
         }
         return sum;
      }
}