简体   繁体   English

Java While循环与面向绝对初学者的Java编程中提出的挑战有关

[英]Java While Loop relating to a Challenge presented in Java Programming for the Absolute Beginner

I am attempting to learn Java Programming on my own (without classes/teachers/tutors/etc.) so this is not a homework assignment. 我试图独自学习Java编程(没有上课/老师/辅导老师/等等),所以这不是家庭作业。

My question has been alluded to in Java Challenge for beginners: Generate random numbers in a while loop , however, I have not advanced far enough into this book to have covered ArrayLists, as stated by the prior programmer who asked this question. 我的问题已在Java挑战中针对初学者提到:在while循环中生成随机数 ,但是,正如问这个问题的先前程序员所说,我对本书的介绍还不够深入,无法涵盖ArrayLists。

Answering this question definitely would help most beginner programmers better understand how to write statements for while loops, an often intricate process, especially for beginners. 肯定地回答这个问题将有助于大多数初学者程序员更好地理解如何为while循环编写语句,而while循环通常是一个复杂的过程,特别是对于初学者而言。

The question is: Write a while loop that generates random numbers between 1 and 100 and stops looping after it generates the same number twice. 问题是:编写一个while循环,该循环生成1到100之间的随机数,并在两次生成相同的数字后停止循环。

As you will recognize, running this program only creates an output of two random numbers between 1 and 100, each time it is run. 您将认识到,每次运行该程序时,它只会创建两个介于1和100之间的随机数的输出。 I believe this error is encountered due to line 17: equal = numberCheck == values[i]; 我相信由于第17行而遇到此错误:equal = numberCheck == values [i]; being incorrect since this is the statement defining when the while loops condition becomes true and therefore stops evaluating. 是不正确的,因为这是定义while循环条件何时变为真并因此停止求值的语句。

Any help is greatly appreciated. 任何帮助是极大的赞赏。 Thank you. 谢谢。

My code is: 我的代码是:

import java.util.Random;

public class SameNumber {

    public static void main(String args[]) {

        Random rand = new Random();
        int[] values = new int[100];
        int counter = 0;
        boolean equal = false;

        for (int i = 0; i < 2; i++) {
            values[i] = rand.nextInt(100) + 1;
            System.out.println(values[i]);
            int numberCheck;
        }

        while (!equal) {
            for(int i = counter - 1; i >= 0; i--) {
                int numberCheck = values[i];
                equal = numberCheck == values[i];
             //}
                if (!equal) {
                    System.out.println(rand.nextInt(100) + 1);
                }

                for (int j = counter - 1; j >= 0; j--) {
                    if (numberCheck  == values[j]) {
                        break;
                    }
                }
            }
        }
    }
}

PS: I understand that this may sound ridiculous, however I have been working on this problem for about a week and trying to gather additional research, and I still could not arrive at the proper solution. PS:我知道这听起来很荒谬,但是我已经在这个问题上研究了大约一个星期,并试图收集更多的研究成果,但是我仍然无法找到合适的解决方案。 I have been hesitant to ask for help since I am concerned that other programmers would answer with methods that I have not yet learned. 我一直很犹豫地寻求帮助,因为我担心其他程序员会使用我尚未学习的方法进行回答。

Your approach is pretty indirect...let's just try it by directly following the instructions: 您的方法非常间接...让我们直接按照说明进行尝试:

  1. Generate a new random number 产生一个新的随机数
  2. Determine if you've seen this random number before 确定您之前是否看过此随机数
  3. No? 没有? Record that you've seen this random number and go to 1. 记录您已看到此随机数,然后转到1。
  4. Yes? 是? Stop 停止

Then the real question is, "how do I determine if I've seen the random number before?". 然后,真正的问题是:“如何确定我之前是否看过随机数?”。

Since it's a finite set, you can have a boolean array ( boolean seen[100] ) that you initialize to false. 由于它是一个有限集,因此您可以拥有一个初始化为false的布尔数组( boolean seen[100] )。 Whenever you see a number, mark seen[<number>] as true . 每当您看到一个数字时,请将seen[<number>]标记为true If seen[<number from 2>] is ever true, you've generated it before. 如果seen[<number from 2>]为真,则您之前已经生成了它。

Using an ArrayList to track these things, by the way, wouldn't be the best choice for data structures. 顺便说一句,使用ArrayList跟踪这些事情并不是数据结构的最佳选择。 When you're ready to look at Java collections, check out HashSet , which has constant time (does not depend on the size of the list) execution for contains . 当您准备好查看Java集合时,请查看HashSet ,它具有一个固定时间(不取决于列表的大小)来执行contains

I would set values to be an array of boolean values, and set it to true if your number is there. 我会将values设置为布尔值数组,如果您的数字在那里,则将其设置为true。 Then you would just use your random number as the index to that array: 然后,您将使用随机数作为该数组的索引

boolean[] values = new boolean[100];

int index = Random.nextInt(100);
while(!values[index]){
    System.out.println(index+1);
    values[index] = true;
    index = Random.nextInt(100);
}

try this: 1. Create a random number between 0 to 100 2. Add it to the list if it is not already inside it. 尝试以下操作:1.创建一个介于0到100之间的随机数。2.如果尚未将其添加到列表中,则将其添加到列表中。 3. If the newly generated number is already inside arraylist stop 3.如果新生成的数字已经在arraylist中,则停止

import java.util.ArrayList;
import java.util.Random;

public class SameNumber {
    public static void main(String args[]) {
        Random rand = new Random();
        ArrayList<Integer> list=new ArrayList<Integer>();       
        int newRand=rand.nextInt(100);
        while(!list.contains(newRand)){
            list.add(newRand);
            newRand=rand.nextInt(100);
        }
        System.out.print(list);
    }
}

Even though this is not homework (I hope this doesn't start a trend of homework questions claiming to be non-homework), I still think you are more helped by a pointer, rather than a solution. 即使这不是家庭作业(我希望这不会引发声称是非家庭作业的家庭作业问题的趋势),但我仍然认为您会得到更多的帮助,而不是解决方案。

I'll rewrite what your code actually does in pseudo-code English so you can see where you are going wrong. 我将用伪代码英语重写您的代码实际执行的操作,以便您可以查看出哪里出了问题。

Create a random number generator
Create a 100 element array
Initialize a counter
Initialize a boolean
Loop twice and assign two random numbers to the first
     two elements in the 100 element array (this is a problem)
In the loop: Print out the value of the number assign
In the loop: Meaningless line that will be ignored by the compiler
Start a loop until the boolean initialized above becomes true
Start a loop, initializing the counting variable to -1,
    that will stop when it is greater than or equal to zero, decreasing it
    every time (that means this will never run).
In the loop: Reference an illegal position in the array (-1 and below)
    and assign it to a variable (this is a problem)
In the loop: Check if the variable you just assigned equals what
    you just assigned it (this is a problem)
In the loop: If it doesn't (that can't happen) print out some random number
    unrelated to anything that has happened until now (this is a problem)
In the loop: Start a nested loop with the same issues as the other loop
In the nested loop: check through all the values
    (although they are illegally referenced) in the array equals the number
    pulled from the outer loop. [This is kind of a point, but there are just
    too many problems up to this point to even think about correcting this line]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM