【问题标题】:Random number sequence that stops with 2 equal numbers以 2 个相等的数字停止的随机数序列
【发布时间】:2012-11-29 15:03:57
【问题描述】:

创建一个由 0-9 的数字组成的数字序列,如果两个数字背靠背出现,则结束序列并显示序列的长度。

我一直在尝试找到一种方法来编写具有上述要求的程序。我只是想不出办法来做到这一点。我得到的最多的是:

import java.util.Random;
public class RandomSequence{
  public static void main(String[]args){
    int num1, num2, num3, i=2;
    Random r=new Random();
    num1=r.nextInt(10);
    num2=r.nextInt(10);
    System.out.print(num1+", "+num2+", ");
    while (num1!=num2){
      num3=r.nextInt(10);
      i++;
      System.out.print(num3+", ");
      if (num3==num2){
        System.out.println("There are "+i+" numbers in the sequence");

..

当两个相等的数字背靠背出现时,我只是不知道如何结束序列。

举个例子:

1,6,2,9,8,1,4,2,8,2,2

这个序列有 11 个数字。 "

谢谢您,非常感谢您的帮助!

【问题讨论】:

  • 背靠背的意思是if (current_number == previous_number) {

标签: java random sequence


【解决方案1】:

我没有看到 num2 发生变化的任何地方。您希望 num2 保存您在上一次循环迭代中生成的数字。因此,在循环结束之前,您需要设置 num2 = num3;

真的,根本不需要 num3。您在循环之前设置为分别使用 num1num2 作为前一个和当前数字,然后将 num3 添加到组合中。重命名“num1”和“num2”(比如“previous”和“current”)可能有助于弄清楚发生了什么。

刚刚注意到,还有一个小问题。如果第一项和第二项相等,则根本不会通过循环,因此会错过输出。您应该在循环退出后输出(毕竟 while 条件已经在检查是否相等)。

========

类似这样的:

 get first number, store as 'previous'.
 get second number, store as 'current'.
 print first couple numbers
 while (previous!=current){
   count up.
   move 'current' to 'previous'
   get next number, store as 'current'
   print current value
}
print final count

【讨论】:

  • 好吧,我只是想不出还有什么可以放在后面的。
【解决方案2】:
    import java.util.Random;
public class RandomSequence{
  public static void main(String[]args){
    int num1, num2, num3, i=2;
    Random r=new Random();
    num1=r.nextInt(10);
    num2=r.nextInt(10);
    System.out.print(num1+", "+num2);
    while (num1!=num2){
      num1=num2;
      num2=r.nextInt(10);
      i++;
      System.out.print(", "+num2);
    }
    System.out.println("\n\nThis sequence consists of "+i+" numbers");
  }
}

非常感谢 femtoRgon。 我接受了您的提示并重新编辑了程序,它运行良好。这比我想象的要容易(我想多了)。

再次感谢您!

【讨论】:

    【解决方案3】:

    使用 ArrayList 会很容易

    import java.util.ArrayList;
    import java.util.Random;
    public class RandomSequenceB {
     public static void main(String[]args){
       int i=0;
       ArrayList sequence = new ArrayList();
    
       while (true) {
         sequence.add(new Random().nextInt(10));
         System.out.println(sequence);
         if (i > 1 && sequence.get(i) == sequence.get(i - 1)){
           System.out.println("There are "+i+" numbers in the sequence");
           break;
         }
         i++;
       } 
     }   
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-14
      • 2023-03-18
      • 1970-01-01
      • 2017-06-14
      • 2021-04-17
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多