【问题标题】:Java: Sorting an array of number StringsJava:对数字字符串数组进行排序
【发布时间】:2015-06-27 06:29:04
【问题描述】:

我的想法/问题:

我正在处理 Java 挑战(说明如下)。我已经第 1/2 部分“几乎”完成(如下代码所示)。

正如您将在我的代码中看到的,我正在从 .txt 文件中读取数据。

longnums.txt 的前 20 行:

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
44274228917432520321923589422876796487670272189318
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145

如说明(如下)所述,我已将.txt100行放入一个数组中,每个元素的值 em> 由 50 个“数字/数字/字符”组成。

以上步骤完成后,我要:1) 将'them'按大小排序(最小的数字在前),2) 将此文件保存为p5a .txt 在 answers 目录中,3) 找到所有 100 个数字之和的前 10 位,并将答案打印到控制台。

以上是我对路线的理解(他们在下面发布)。

上面的1 & 3有问题。

我做错了什么/我该如何解决它/我需要做什么来完成这项任务/我如何改进我的代码?

挑战路线:

使用资源目录中的longnums.txt文件解决这个问题。

第 1 部分: 构建 longnum.txt 中包含的 100 个数字(每个 50 位长)的数组em>,并根据大小对它们进行排序(最小的数字在前)。将此文件另存为 p5a.txt 在 answers 目录中。

第 2 部分:找出所有 100 个数字之和的前 10 个数字,并将答案打印到控制台。 p>

显示输出和目录的图片链接:

http://screencast.com/t/pp1aRbjM

我当前的代码:

package app;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

public class LargeSums {
    private static FileReader fb;
    private static BufferedReader bf;
    private static PrintWriter pw;
    private static String out = null;
    private static  int sum;

    public static void main(String[] args) throws IOException { 
        fb = new FileReader("resources/longnums.txt");
        bf = new BufferedReader(fb);
        pw = new PrintWriter(new BufferedWriter(new FileWriter("answers/p5a.txt")));

        while ((out = bf.readLine()) != null) {
            String[] sortedStr = out.split(" ");
            Arrays.sort(sortedStr); // Might not need this line

            for (int i = 0; i < sortedStr.length; i++) {
            // TO-DO: sort them according to size (smallest numbers first).

            pw.println(sortedStr[i]); // Save this file as p5a.txt in the answers directory
            System.out.println(sortedStr[i]);// print to console just to see output

            // sum = sum + Integer.parseInt(sortedStr[i]); 
            // something like the above line to total the sum of all the numbers
            }
            // TO-DO: Find the first 10 digits of the sum of all 100 numbers, and print the answer      
            // to the console.  
        }
    }
}   

【问题讨论】:

  • 我已经尝试/查看了很多东西。但是我很难得到一些东西来工作/把它拉在一起。森林穿过树木,大概。我会看看你的链接。
  • 2 提示:整数可能不是此类 BIG 数字的正确数据类型。你应该在最后关闭你使用的作家。
  • 长对吧? & 我和你一起讨论 .close()。谢谢。

标签: java arrays string sorting readline


【解决方案1】:

嗯?另一个答案去哪儿了?

好的,这并不是你所要求的——但我敢说它可能会更好。稍后会详细介绍。

package org.example;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class Main {
    private static final Path INPUT_FILE_PATH = Paths.get("./resources/longnums.txt");
    private static final Path OUTPUT_FILE_PATH = Paths.get("./answers/p5a.txt");

    public static List<BigInteger> readDataFromFile() throws IOException {
         return Files.readAllLines(INPUT_FILE_PATH).stream().map(BigInteger::new).collect(toList());
    }

    public static String calculateFirst10DigitsOfSum(List<BigInteger> numbers) {
        BigInteger sum = numbers.stream().reduce(BigInteger.ZERO, (a,b) -> a.add(b));
        return sum.toString().substring(0, 10);
    }

    public static void writeLinesSortedToFile(List<BigInteger> numbers) throws IOException {
        List<String> outputLines = numbers.stream().sorted().map(BigInteger::toString).collect(toList());
        Files.write(OUTPUT_FILE_PATH, outputLines, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
    }

    public static void main(String[] args) throws IOException {
        List<BigInteger> data = readDataFromFile();
        writeLinesSortedToFile(data);
        String first10Digits = calculateFirst10DigitsOfSum(data);
        System.out.println(first10Digits);
    }
}

它可以写得更短,但我想用一些方法来告诉你这里发生了什么。

严重依赖

  • 流(Java 8 中引入)
  • 新的文件 IO(Java 7 中引入)

有了这些东西,它就不能很好地融入截屏视频给你的骨架。但是在这种情况下,我会认为截屏框架已经过时了。

我不确定你是否想使用 Streams,但我肯定会推荐使用新的文件 IO。 Files.readAllLines 看起来确实比那些 InputReaders 更吸引人,不是吗? ;)

我不认为这是填写此截屏视频的理想代码,但这是我今天编写的代码(与截屏视频相比,它看起来有点过时)来解决问题。

【讨论】:

    猜你喜欢
    • 2012-10-14
    • 2021-03-21
    • 1970-01-01
    • 2011-11-12
    • 2017-06-07
    • 2014-08-02
    相关资源
    最近更新 更多