【问题标题】:Generating 100 random numbers and comparing them to user inpuit生成 100 个随机数并将它们与用户输入进行比较
【发布时间】:2021-10-22 17:35:58
【问题描述】:

所以我在这个问题上玩得很开心。我需要向用户询问一个值,然后生成 100 个随机数并计算用户输入值以上的奇数个数。我迷路了,只想把电脑扔在街上!请帮忙!谢谢你!我已经在下面发布了到目前为止的内容。

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
    
         Scanner input = new Scanner(System.in);
            System.out.println("Enter a value between 30 and 70: ");
        
           while (true) { 
            int user = input.nextInt();        
            if (user > 70)
               System.out.println("Value higher than 70, Please re-enter value: ");
            else if (user < 30)
              System.out.println("Value lower than 30, Please re-enter a value: ");
            else
              System.out.println("The value entered by the user is " + user);

     }
 }

【问题讨论】:

  • 随机值在什么范围内?

标签: java


【解决方案1】:

从用户那里得到一个值后,使用for循环,迭代一百次,在每一轮,你生成一个随机数(选择边界)然后添加条件和计数

Scanner input = new Scanner(System.in);
System.out.println("Enter a value between 30 and 70: ");

int user;
while (true) {
    user = input.nextInt();
    if (user > 70) {
        System.out.println("Value higher than 70, Please re-enter value: ");
    } else if (user < 30) {
        System.out.println("Value lower than 30, Please re-enter a value: ");
    } else {
        System.out.println("The value entered by the user is " + user);
        break;
    }
}
int count = 0;
Random r = new Random();
for (int i = 0; i < 100; i++) {
    int rnd = r.nextInt(100);
    if (rnd > user && rnd % 2 == 1) {
        count++;
    }
}
System.out.println("There is " + count + " values odd numbers above your value");

【讨论】:

    【解决方案2】:

    我建议用随机数填充一个数组,然后循环遍历它。以下是一些可能对您有所帮助的链接:

    Generating random numbers

    Generating an array filled with random numbers

    Looping through arrays

    Check if a number is odd

    【讨论】:

    • 非常感谢您的帮助。非常感谢!
    猜你喜欢
    • 2020-09-17
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多