Java以指定格式输入数字

package com.ylx;
import java.text.DecimalFormat;

public class Test {
    public static void main(String[] args) {
        //测试方法
        System.out.println(formatNumber("14","00000"));
        System.out.println(formatNumber(150,"00000"));
    }
    /**
     * @param String类型的数字   如"150"
     * @param 格式化格式  ,如“00000”
     * @return 格式化后的字符串
     */
    public static String formatNumber(String str,String formatAs){
         DecimalFormat df=new DecimalFormat(formatAs);
         String str2=df.format(Integer.parseInt(str));
        return str2;
    }
    /**
     * @param int数字   如150
     * @param 格式化格式  ,如“00000”
     * @return 格式化后的字符串
     */
    public static String formatNumber(int num,String formatAs){
         DecimalFormat df=new DecimalFormat(formatAs);
         String str2=df.format(num);
        return str2;
    }
}

 

转载于:https://www.cnblogs.com/tomcattd/p/3144063.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题涉及两个部分:生成随机红包金额和计算尾数出现指定数字的概率。 首先,我们可以使用Java的Random类生成随机红包金额。具体来说,可以定义一个函数,输入红包总金额和红包个数,输出一个数组,包含每个红包的金额。 ```java import java.util.*; public class RedPacket { public static int[] generate(int totalAmount, int count) { Random random = new Random(); int[] result = new int[count]; for (int i = 0; i < count; i++) { if (i == count - 1) { result[i] = totalAmount; } else { int maxAmount = (totalAmount - (count - i - 1)) / 2; int amount = random.nextInt(maxAmount) + 1; result[i] = amount; totalAmount -= amount; } } return result; } } ``` 接下来,我们需要计算尾数出现指定数字的概率。具体来说,可以定义一个函数,输入一个数组和一个数字,输出出现该数字的概率。 ```java public class Probability { public static double calculate(int[] amounts, int digit) { int count = 0; for (int amount : amounts) { if (amount % 10 == digit) { count++; } } return (double)count / amounts.length; } } ``` 最后,我们可以将两个函数结合起来,实现抢红包程序。具体来说,可以定义一个函数,输入红包总金额、红包个数和尾数指定数字,输出抢到该数字的概率。 ```java public class RedPacketGame { public static double play(int totalAmount, int count, int digit) { int[] amounts = RedPacket.generate(totalAmount, count); return Probability.calculate(amounts, digit); } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { int totalAmount = 100; int count = 10; int digit = 6; double probability = RedPacketGame.play(totalAmount, count, digit); System.out.println("The probability of getting digit " + digit + " is " + probability); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值