所以我正在做一個描述生成器,並在「:」分裂一個文本文件。因此,如果文本文件有「dog:fish:cat:bird」,我的代碼會將其拆分爲「:」並隨機選取一個。但是,當我打印出結果時,輸出結果都是一樣的。它會隨機選擇數組中的單詞,但如果我說生成它4次,它將是4次相同的事情。那麼我的邏輯在哪裏是錯誤的如何解決這個問題?我想讓它打印4個隨機不同的東西。我的代碼如下:如何隨機化一個字符串的數組,因此它每次都是不同的循環
公共類發電機 {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Random r = new Random();
System.out.print("Enter a file name: ");
String fName = scanner.nextLine();
File infle = new File(fName);
Scanner read = new Scanner(infle);
System.out.print("Enter number to make: ");
int things = scanner.nextInt();
System.out.println();
System.out.println("Here are " + things + " things: ");
System.out.println();
//gets random animal
String animal = read.nextLine();
String[]anm1 = animal.split(":");
int rnd_Animal = r.nextInt(anm1.length);
String rndAnimal = (anm1[rnd_Animal]);
//gets random adjective
String adj = read.next();
String []adj1 = adj.split(":");
int rndAdj = r.nextInt(adj1.length);
String randomAdj = (adj1[rndAdj]);
for(int i=0; i <things; i++)
{
System.out.println(randomAdj + " " + rndAnimal);}
所以,我的輸出將打印這樣的:「汗魚」多次,我輸入了要生成它。如果我輸入3個描述來生成,我怎麼能說出「出汗的魚」,「臭狗」,「慢魚」?感謝您的任何幫助。
我認爲你需要在for循環中放置「獲取隨機動物」和「獲取隨機形容詞」代碼塊。 – Surely