【问题标题】:Java: Methods, Files, and ArraysJava:方法、文件和数组
【发布时间】:2015-07-11 20:53:01
【问题描述】:

我应该编写一个应用程序,该应用程序可以从硬编码的文本文件中读取名称,将它们保存为字符串数组,然后将这些名称写入不同的文本文件中,但已排序。我相信我已经完成了前两部分,但我对如何对名称进行排序然后将它们写入新文件感到困惑。

这是我正在处理的实际问题:

“获取一个包含 10 个名称的输入文件(硬编码)。编写一个程序来读取文件,将名称保存在字符串数组中,然后按排序顺序写入不同的文件名。适当地使用方法。”

顺便说一句,我是一名新手程序员,这就是我目前所拥有的。

public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here
    readFile();
    saveStringArray();
}

public static void readFile() {
    File file = new File("/Users/nicoladaaboul/Desktop/Programming/C++, "
        + "HTML5, Java, PHP/Java/Question2/names.txt");
    try {
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) {
            String i = sc.next();
        }
        sc.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

public static void saveStringArray() throws FileNotFoundException {
    String token1 = "";
    Scanner inFile1 = new Scanner(new File("names.txt")).useDelimiter(",\\s*");
    List<String> temps = new ArrayList<String>();

    while (inFile1.hasNext()) {
        token1 = inFile1.next();
        temps.add(token1);
    }

    inFile1.close();
    String[] tempsArray = temps.toArray(new String[0]);
    Arrays.sort(tempsArray);

    for (String s : tempsArray) {
        System.out.println(s);
    }
}

public static void sortingNames() {
}

public static void writingFile() throws FileNotFoundException {
    PrintWriter writer = new PrintWriter("sortedNames.txt");
    writer.close();
}

【问题讨论】:

  • 你应该在提问时表现出一些努力(代码)。
  • 不清楚你的问题是什么。如果你能提出一个具体的问题,你就会得到一个具体的答案。但目前尚不清楚你能做什么和不能做什么,以及你被困在哪一点上。或者,如果您想找人为您编写代码,您可以在其他网站上聘请编程人员。
  • Is this a homework question? 您能否更具体地说明您在排序和写入文件时遇到了什么问题?

标签: java arrays file methods


【解决方案1】:

将问题分解为说明非常重要。 1.您需要读取可以使用bufferedReader的文件(代码如下)。 2. 创建一个数组(或数组列表)来存储您的字符串值。 3. 然后,当您读取每一行时,将这些值存储在数组中。 4. 完成读取文件后,您会将这个数组传递给对其进行排序的函数(Why does my sorting loop seem to append an element where it shouldn't?)。 5. 排序后,您只需将此数组写入文件即可。

BufferedReader br = new BufferReader(new FileReader("name.txt"));
int count = 0;
String line;
String[] names = new String[100];
while((line = br.nextLine()) != null){
    names[count] = line;
    count++;
}

【讨论】:

  • 所以你输入的几乎是两种方法合二为一,它会从文件中读取它,同时将它存储在一个字符串数组中?
猜你喜欢
  • 1970-01-01
  • 2013-12-31
  • 2012-03-07
  • 2017-03-12
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多