有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我需要在一个数组中添加1000个介于1和100之间的整数及其出现次数,然后显示它们

本作业的说明如下:

Text file numbers.txt contains 1000 integers vary from 1 to 100. You need to

  1. Use an ArrayList (Required) to store all integers. If one number appears multiple times in text file, only save the first occurrence in the ArrayList.

  2. The output should be saved in one txt file called results.txt

  3. The output information should be in the following format in the text file.

Numbers 1 to 100 should be in the first column in the order of appearance. Second column presents the occurrence times of the corresponding number.

以下是我在意识到数字必须按照它们最初出现在数字中的顺序之前所做的尝试。文本

import java.util.Scanner;

导入java。io.*; 导入java。util。阵列

public class test
{
   public static void main(String [] args) throws FileNotFoundException
   {   
  
      Scanner fileInput = new Scanner(new File("numbers.txt"));             
      PrintWriter fileOutput = new PrintWriter(new File("results.txt"));
  
      int cols;
      int rows;
       
      int[][] b = new int [101][2];
      int i = 0;

      int temp;     
      int[] a = new int [1000];
  
      while (fileInput.hasNext())
      {
         a[i] = fileInput.nextInt();
         i++;
      }
                   
      for (int f = a.length - 1; f > 0; f--)
      {
         for (int j = 0; j< f; j++)
         {
            if (a[j] > a[j + 1]) 
            {
               temp = a[j];
               a[j] = a[j + 1];
               a[j + 1] = temp;
            }
         }
      }
  
      int s = 1;
      int t = 0;
  
      for(int w = 0;w < a.length; w++)
      {
         if (s==a[w])
     {
        t++;
        b[s][0]=s;
     }else if(s<=a[w])
         {
            s=a[w];
        
            b[s][1]=t;
            t=0;
        
            t++;
         }
      }
  
      for (int[] arr : b) 
      {
         System.out.println(Arrays.toString(arr));

我真的不知道该怎么办。我最初使用了冒泡排序,然后我就能够通过它来进行排序,但我注意到,在最后,数字必须按照外观的顺序排列。任何帮助都将不胜感激!谢谢


共 (3) 个答案

  1. # 1 楼答案

    我建议您不要在这里使用arraylist,因为您需要调用contains()的每个号码都需要O(n)个时间。您最好使用HashMap或LinkedHashMap(如果您需要维护插入顺序),这会占用较少的时间。将每个数字存储为键,将出现项存储为值

  2. # 2 楼答案

    您应该先将读取数添加到数组列表中,计数为1。 如果读取的编号已在列表中,则增加计数。 稍后迭代ArrayList并将数字和计数打印到结果文件中

    不需要排序

  3. # 3 楼答案

    分阶段解决问题,小步骤通常比在头脑中构建完整的解决方案、将其全部敲碎,然后想知道哪个部分有缺陷要快得多。(提示通常有多个bug)这会从数组列表的输入中获取所有数字:

    ArrayList<int> nbrs = new ArrayList<int>();    
    while (fileInput.hasNext()) {
      nbrs.add(fileInput.nextInt());
    }
    

    但它并没有忽略重复,有没有ArrayList方法可以帮助您?检查Javadoc会告诉您是的。所以重构:

    ArrayList<int> nbrs = new ArrayList<int>();    
    while (fileInput.hasNext()) {
      int i = fileInput.nextInt();
      if (!nbrs.contains(i)) {
        nbrs.add(i);
      }
    }
    

    现在输入的所有数字都按顺序排列,没有重复。但是您仍然需要计算重复项,并输出所有内容。一次又一次地重构。。。玩得高兴对付山羊的方法很多