我是java的新手,我非常接近答案。我希望我能得到一些提示,但不是完整的答案。我宁愿自己推导出逻辑。
/*
Write a method named makeGuesses that will guess numbers
between 1 and 50 inclusive until it makes a guess of at least 48.
It should report each guess and at the end should report
the total number of guesses made. Below is a sample execution:
*/
guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5
public void makeGuesses(){
Scanner sc=new Scanner(System.in);
Random rnd=new Random();
int i=1
int counter=0;
while(i>=1 && i<=50){
i=rnd.nextInt();
System.out.println("guess = " + i);
counter++;
}
System.out.print("total guesses = "+ counter);
}
我的代码出了什么问题?我意识到虽然我把我的i修复到1到50之间,但它仍然超过了。
答案 0 :(得分:2)
您必须在rnd.nextInt();
中指定您的情况
rnd.nextInt(50) + 1; // (1 - 50)
并检查您的情况,否则您的计划将永远不会停止
while(i>=1 && i<=50)
查看文档:
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
以下是java.util.Random.nextInt()方法的声明。
public int nextInt(int n)
参数 n - 这是要返回的随机数的界限。必须是积极的。
返回值 方法调用返回伪随机,均匀分布的int值介于0(包括)和n(不包括)之间。