【问题标题】:How to randomize an array of a String so it is different every time though the loop如何随机化一个字符串数组,以便每次循环都不同
【发布时间】:2016-08-26 01:27:00
【问题描述】:

所以我正在制作一个描述生成器,并在“:”处拆分一个文本文件。因此,如果文本文件有“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 循环中。

标签: java arrays loops


【解决方案1】:

问题是您在 for 循环之外获得了 rndAnimal 和 randomAdj 的值。所以它随机获取值 ONLY ONCE 并显示四次。要解决此问题,请将值分配给循环内的两个字符串。

for(int i=0; i<things; i++){

    //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]);

    System.out.println(randomAdj + " " + rndAnimal);
}

【讨论】:

  • 绝对是这样。但是,我在那里有几个其他随机对象,我得到一个“找不到行错误”。我的随机对象的顺序是,nextLine,nextLine,nextLine,nextLine,nextLine。我在那里有下一个,因为它从那个数组中取了两次,我一直在翻转 nexLine 和下一个,但似乎无法得到它。任何想法,即使这听起来令人困惑?
  • 为了解决这个问题,我建议你先处理对象的范围,然后检查文本文件。您可能遇到文件 I/O 问题,您可以寻找解决方案,但您在问题中寻求帮助的问题已经解决。看看有没有帮助。
  • 在进一步检查您的代码后,如果我将所有内容都放在 for 循环中,它将从其他行中获取单词,这不是我需要它做的。它必须仅从该行中获取文本文件中的随机单词,这就是为什么我得到一个 line not found 错误。
  • 或者您也可以做一件事,从您想要的任何一行获取输入并将其存储在字符串 var 中。现在忘记文件。使用字符串作为您的来源。这会让事情变得简单。使用循环外的主字符串生成循环内的随机字符串。
  • 我所要做的就是将我最终的随机字符串放入循环中,并将其他所有内容放在外面,它可以完美运行。非常感谢您的所有帮助。
猜你喜欢
  • 2018-09-08
  • 1970-01-01
  • 2014-06-10
  • 2016-04-12
  • 2015-09-03
  • 1970-01-01
  • 2013-05-14
  • 2012-07-24
  • 2012-03-04
相关资源
最近更新 更多