【发布时间】:2021-06-17 07:53:15
【问题描述】:
我是 Java 新手,我遇到的问题是我总是得到 0 个大于用户值的随机数,并且每次运行程序时我应该得到不同数量的大于值的随机数
package chapterfinal;
import java.util.Scanner;
public class finalf {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int greaterOrequal = 0;
int count = 0;
final int finalcount = 100;
System.out.println("Enter a value between 30 and 70: ");
int value = input.nextInt();
while (value > 70 || value < 30) {
System.out.println("Please try to enter a value between 30 and 70: ");
value = input.nextInt();
}
for (count = 0; count < finalcount; count++) {
int random = (int) Math.random() * 100;
if (random >= value)
greaterOrequal++;
}
System.out.println("There are " + greaterOrequal + " random numbers greater than " + value);
} }
“while”代码是提示用户重新输入一个介于 30-70 之间的值,以防用户输入超出该范围的内容。
“for”代码是生成 100 个随机数,并分析有多少个大于用户输入的值。
最后只打印有多少随机数大于该值的结果并打印用户输入的值
我知道是一个非常简单的代码,我找不到它有什么问题!
这是我得到的结果:
Enter a value between 30 and 70:
80
Please try to enter a value between 30 and 70:
50
There are 0 random numbers greater than 50
它应该是这样的:
Enter a value between 30 and 70:
25
Please try to enter a value between 30 and 70:
50
There are 51 random numbers greater than 50
每次我运行程序时,我应该得到比用户值更大的不同数量的随机数。
希望大家能帮帮我
请提供任何帮助!
【问题讨论】:
标签: java eclipse for-loop random while-loop