【问题标题】:Adding a value to a sorted array in Java 8在 Java 8 中向排序数组添加值
【发布时间】:2015-11-19 07:00:19
【问题描述】:

为您提供以下列表,其中包含现代历史的(半随机)年份。将列表保存到名为“events.txt”的文本文件中编写一个程序:

  1. 读取文件“events.txt”
  2. 先按最新事件排序
  3. 确定 1892 年 CMU 的成立是否被视为世界历史事件
  4. 如果还没有,将事件添加到事件列表中
  5. 将新的事件列表写入名为“sorted_events.txt”的文件
import java.io.*;
import java.util.*;

public class EventSorter {
public static void main(String[] args) throws FileNotFoundException{

    File file =new File("events.txt");
    FileReader read = new FileReader(file);
       LineNumberReader lines = new LineNumberReader(read);
       Scanner readIn = new Scanner(file);
       PrintWriter output = new PrintWriter("sorted_events.txt");

    try{

        //call for the file

//make sure it exists
        if(file.exists()){
            {
            //first write this to determine the number of lines
           int lineNumber = 0;
           //gets the number of lines
               while (lines.readLine() != null){
              lineNumber++;
               }
               int[] event = new int[lineNumber];
               int j = 0;
               while(readIn.hasNext()){

                  event[j]=readIn.nextInt();
                  j++;

               }
               //sort the array
               Arrays.sort(event);
               boolean found;
               for(int i = 0; i < event.length; i++){
                  if (event[i] == 1892){
                      //see if 1892 is on the list
                      System.out.println("CMU is a historic event");
                      found = true;
                  }
                      else{
                          addElement(event, 1892);
                      }
                  }

                  int[] sortedEvent = new int[lineNumber];
               for(int k = 0; k < event.length; k++){
                  sortedEvent[k] = event[(event.length-1) - k];
               System.out.println(sortedEvent[k]);
               }
               for(int print = 0 ; print < event.length; print++){
                  output.println(sortedEvent[print]);

               }
        }
               readIn.close();
               output.close();
               lines.close();




        }else{
            System.out.println("File does not exist!");
        }
        }
        catch(IOException e){
        e.printStackTrace();
    }

}

static int[] addElement(int[] a, int e) {
   a  = Arrays.copyOf(a, a.length + 1);
   a[a.length - 1] = e;
   return a;

}


}

【问题讨论】:

  • 你是从考试中复制的还是什么?
  • 不,这是一个家庭作业,我不知道该怎么做我不知道如何将元素 1892 添加到新的排序 txt 文件中
  • 现在我看着它,它看起来像是我这样做了,但是知道,我复制了作业的说明,所以你可以看到我猜想我在做什么。
  • 您的实际问题是什么?

标签: java arrays sorted


【解决方案1】:

我将严格回答标题“在 Java 8 中向排序数组添加值”。有两种选择:

  1. 从您的数组中创建一个TreeSet 或任何SortedSet(或基于二叉搜索树的结构)。此集合默认排序,您添加到其中的任何新项目都将保持排序。

  2. 使用类似于二分搜索的方法来查找数组中应放置新元素的位置。

【讨论】:

    【解决方案2】:

    这个程序做你想做的,完美回答老师的问题。

    但是,它使用了几种先进的 Java 技术,我强烈怀疑你的老师会不会给你任何荣誉。因此,使用它需要您自担风险。

    您可以使用此代码做的最好的事情就是阅读它,理解它的概念并将它们结合到您所知道的内容中。

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class EventSorter {
    
      public static void main(String[] args) {
        try {
          Path inPath = Paths.get("events.txt");
          Path outPath = Paths.get("sorted_events.txt");
          int event = 1892;
          Comparator<Integer> lastFirst = Comparator.<Integer>naturalOrder().reversed();
    
          List<Integer> events = Files.lines(inPath).map(Integer::valueOf).sorted(lastFirst).collect(Collectors.toCollection(ArrayList::new));
          int pos = Collections.binarySearch(events, event, lastFirst);
          if (pos < 0) {
            events.add(~pos, event);
          }
          Files.write(outPath, events.stream().map(Object::toString).collect(Collectors.toList()));
        } catch (IOException ex) {
          System.out.println(ex.getMessage());
        }
      }
    }
    

    events.txt(输入)

    1982
    1821
    1934
    1809
    

    sorted_events.txt(输出)

    1982
    1934
    1892
    1821
    1809
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2021-11-14
      • 2021-08-19
      • 1970-01-01
      • 2018-09-22
      相关资源
      最近更新 更多