【问题标题】:How to read in a list of numbers 1-6 and count the repeated numbers java [closed]如何读入数字1-6的列表并计算重复的数字java [关闭]
【发布时间】:2021-02-16 17:13:52
【问题描述】:

所以我试图从一个文件中读取,其中包含超过 10000000 个数字,范围为 1-6。本质上,这个练习的重点是模拟掷骰子,我需要找到每个数字被掷出的概率。我编写了将随机数 1-6 写入文件的代码:

public static void main(String[]args)throws IOException{
    Scanner kb = new Scanner(System.in);
    PrintWriter pw = new PrintWriter(new File("Rolls.txt"));
    System.out.println("Input a number for the amount of rolls");

    long rolls = kb.nextLong();

    for(int i = 0; i< rolls; i++){
        
        if(i % 20 == 0){
            pw.println();
        }
        else{
        pw.print(((int)(Math.random()*6)+1) + ",");
        }
    }


   
    pw.close();
}

所以使用这个文件,我想我应该将整行作为字符串读取,然后以逗号分隔该行,然后将字符串更改为 longs/ints。我正在努力解决的是我应该计算 1 .... 6 的数量并将该数字存储到另一个数组中,然后获取该数组的每个元素并找到它被滚动的概率。到目前为止,我为第二部分提供的代码如下。我尝试了一些东西,但没有任何效果,我被难住了。

public static void main(String[]args) throws IOException{
    Scanner in = new Scanner(new File("Rolls.txt"));
    long[] list = {0,0,0,0,0,0};
   
    while ( in.hasNextLine()){
        String line = in.nextLine();
        String[] numbers = line.split(",");
       
       
    }

感谢任何帮助。谢谢!

【问题讨论】:

  • 您需要遍历numbers 中的项目,将每个项目从字符串转换为整数(参见Integer.parseInt),然后在line 中的相应索引处递增项目(即line[roll]++).
  • 您遇到了什么具体问题?您尝试了哪些方法,但没有成功?
  • “我尝试了一些东西,但没有工作”不是一个有效的问题描述。

标签: java simulation dice


【解决方案1】:

Kamen Vakavchiev 和 Alexandre Hassan 的回答很好,但我想支持另一种方法,使用 Java 8 Stream API 使代码更简单和可读。

BufferedReader reader = new BufferedReader(new FileReader("Rolls.txt"));
Map<String, Long> result = reader.lines()
    .flatMap((Function<String, Stream<String>>) s -> Arrays.stream(s.split(",")))
    .collect(Collectors.groupingBy(s -> s, Collectors.summingLong(value -> 1)));
System.out.println(result);

可能的输出是:

{1=166381, 2=166643, 3=167300, 4=166644, 5=166197, 6=166835}

【讨论】:

  • Map&lt;String, Long&gt; freq = reader.lines().flatMap(line -&gt; Arrays.stream(line.split(","))) .collect(Collectors.groupingBy(str -&gt; str,Collectors.counting())); 但我怀疑 OP 是 Java 新手,应该首先关注基础知识。
  • @WJS 非常同意
【解决方案2】:

您用来生成卷的代码表现不佳。它在文件的开头放置了一个空的新行,因为在循环的第一次迭代中 i 等于 0。第二个问题是生成的卷数少于您想要的数量,因为在某些迭代中您只写了一个新行而没有数字。这就是我修改您的代码以正确生成卷的方式。

public static void main(String[]args)throws IOException{
    Scanner kb = new Scanner(System.in);
    PrintWriter pw = new PrintWriter(new File("Rolls.txt"));
    System.out.println("Input a number for the amount of rolls");

    long rolls = kb.nextLong();

    for(int i = 1; i<= rolls; i++){

        if(i % 20 == 0){
            pw.println();
        }
        pw.print(((int)(Math.random()*6)+1) + ",");
    }



    pw.close();
}

下面是用于读取和计算概率的代码的延续。正如一些人已经评论过的,你应该使用 Integer.parseInt();以整数形式获取字符串值。

        public static void main(String[]args) throws IOException{
                Scanner in = new Scanner(new File("Rolls.txt"));
                long[] list = {0,0,0,0,0,0};
                while ( in.hasNextLine()){
                        String line = in.nextLine();
                        String[] numbers = line.split(",");
                        //parse the string to ints
                        for(int i=0;i<numbers.length;i++){
                                int currentValue = Integer.parseInt(numbers[i]);
                                list[currentValue-1]++;
                        }
                }
                long totalRollCount=0;
                for(int i=0;i<list.length;i++){
                        totalRollCount+=list[i];
                }
                System.out.println(totalRollCount);
                for(int i=0;i<list.length;i++){
                        System.out.println((i+1)+" "+((double)list[i]/totalRollCount));
                }
    }

【讨论】:

    【解决方案3】:

    由于您输入的内容都是整数,因此您可能可以将它们用作键

    public static void main(String[]args) throws IOException {
        Scanner in = new Scanner(new File("Rolls.txt"));
        long[] list = {0,0,0,0,0,0};
        int parsed;
    
        while ( in.hasNextLine()){
            String line = in.nextLine();
            String[] numbers = line.split(",");
    
            for (String number : numbers) {
                parsed = Integer.parseInt(number);
                list[parsed - 1]++;
            }
        }
    

    **我没有对此进行测试,但它应该可以工作

    【讨论】:

    • 当我尝试运行它时,我得到一个严重的错误。我得到:线程“main”中的异常。我做错什么了吗?或者这不起作用?
    猜你喜欢
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多