Java Random類はWeChatがお年玉を奪い取ることを実現します。


1、文法:Random r = new Random();Randomクラスは乱数を取得するいくつかの方法を提供する。
  • nextInt()はランダム生成int値
  • を返します。
  • next Long()はランダムlong値
  • を返します。
  • next Double()はランダムDouble値
  • を返します。
  • next Float()はランダムFloat値
  • を返します。
  • next Boolean()はランダムBoolean値
  • を返します。
    最も一般的なのはnextInt(int n)方法であり、パラメータはint値であり、取得範囲は0 <= nextInt(int n) < nであり、0はnに等しくない。
    Random r = new Random();
    System.out.println(r.nextInt(10));
    
    上の出力値は0から10までの間に0になるが、10には永遠についてこない。
    2、Random類を通じて、ちょっとした機能を実現します。WeChatはお年玉を奪い取ります。
    public class Demo{
    	public static void main(Stirng[] args){
    		System.out.println("----------     -----------");
    		Scanner sc = new Scanner(System.in);
    		System.out.println("         ( ):");
    		double total = sc.nextDouble();
    		System.out.println("        ");
    		int bagCount = sc.nextInt();
    		double min = 0.01;//      
    		Random r = new Random();
    		for(int i = 1;i < bagCount;i++){
    			//            =        - (      -        )*     
    			double max = total - (bagCount - i) * min;
    			double bound = max - min;
    			
    			double safe = (double)c.nextInt((int)(bound * 100)) / 100;
    			double money = safe + min;
    			total = total - money;
    			System.out.println(" "+i+"   "+String.format("%.2f",money)+" ");
    		}
    		System.out.println(" "+bagCount+"   :"+String.format("%2f"),total)+" ");
    	}
    }