search

Home  >  Q&A  >  body text

面对对象 - java这段代码为什么不随机的

在看Thinking in Java,有一段实在没看懂

package com.company.allAreTheObjective.Symbol;
import java.util.*;

/**
 * Created by Francis on 12/05/2016.
 */
public class VowelsAndConsonants {
    public static void main(String args[]){
        Random rand = new Random(47);
        for (int i = 0; i < 100; i++){
            int c = rand.nextInt(26) + 'a';
            System.out.print((char)c+","+ c +":");
            switch(c){
                case 'u' : System.out.println("vowel");break;
                case 'w' : System.out.println("Sometimes a vowel");break;
                default  : System.out.println("constant");
            }
        }
    }
}

这一段为什么输出恒为
y,121:constant
n,110:constant
z,122:constant
b,98:constant
r,114:constant
n,110:constant
y,121:constant

PHP中文网PHP中文网2767 days ago405

reply all(3)I'll reply

  • 阿神

    阿神2017-04-17 17:54:36


    The program generates pseudo-random numbers. Your random number seed is fixed at 47. Of course, it will be the same every time. If you want it to be different, you can change the seed to a timestamp or something like that

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:54:36

    Just put itnew Random(47)改成new Random().

    The random numbers generated by the computer are all pseudo-random numbers. As long as the initialization seed given is the same, the generated random number sequence will be the same.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:54:36

    Random objects with the same seed number, the random numbers generated the same times are exactly the same.
    Just change it to Random rand = new Random().

    reply
    0
  • Cancelreply