gpt4 book ai didi

java - 从文件中读取数字并检查随机生成

转载 作者:行者123 更新时间:2023-11-30 08:19:16 25 4
gpt4 key购买 nike

目标:

生成一个随机整数(从 1-99)并使用 numbers.dat 文件(来自上一个实验)确定生成的随机数是否在文件中。不要计算你找到随机数的次数,只输出它在文件中或不在文件中。

可能的伪代码:

  1. 从 1-99 中随机生成一个#
  2. 声明一个 boolean 变量并将其初始化为 false
  3. 循环直到文件末尾或找到匹配项:读取编号。
  4. 比较数字。如果匹配,则设置 Boolean var true
  5. 如果 Boolean 为 true,则该数字已找到,否则未找到。

第 2 部分。将第 1 部分中的所有代码放入一个 for 循环中,以便第 1 部分运行 3 次。b.输出——类似于下面的输出:

The random number 35 is in the file.
The random number 10 is not in the file.
The random number 9 is in the file.

我的代码:

import java.util.*;
import java.io.*;
public class RandomNumberMatch {
public static void main(String[] args) throws Exception {
Scanner num = new Scanner (new File ("numbers.dat"));
Random ran = new Random();
while(num.hasNext()) {
int number = num.nextInt();
int x = ran.nextInt(100);;

if(number == x) {
System.out.println("The number " + x + " is in the file");
}
else {
System.out.println("The number " + x + " is not in the file");
}
}
}
}

输出:

The number 80 is not in the file
The number 52 is not in the file
The number 50 is not in the file
The number 76 is not in the file
The number 21 is in the file
The number 18 is not in the file
The number 40 is not in the file
(Cut short for summary purpose)

文件内容:

16 43 56 8 12 35 65 12 26 3 65 4 75 86 9 79 0 78 5 78 4 63 65 3 53 64 7 5 87 6 96 96 70 7 95 78 46 4 37 46 3 53 93 84 76 56 48 93 3 74 76 46 5 47 38 4 39 4 84 57 46 37 48 4 9 84 7 36 3 0 58 6 7 84 7 5 6 4 9 30 4 3 8 4 7 4 4 55 76 4 53 6 47 5 85 74 63 2 3 45 48 73 63 5 21 42 21 55 1 

除了没有将输出嵌套在 for 循环中之外,我到底做错了什么,这些数字中的大部分都在文件中。我试图将它与我创建的随机数匹配,如果它们相等,则将其输出到文件,然后继续指示该数字是否在文件中。任何帮助将不胜感激,我非常坚持这一点,我似乎无法弄清楚!

最佳答案

因为这看起来像是一项学校作业,所以我不会给你答案的代码,但请考虑以下问题:

你需要判断一个随机数是否存在于整个文件中。因此,如果您将它与文件中的单个数字进行比较,您是否有足够的信息来做出“该数字不在文件中”的明确声明?

如果已经找到要查找的数字,是否还需要继续遍历整个文件?

关于java - 从文件中读取数字并检查随机生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26934967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com