【问题标题】:java program for sorting and returning arrays用于排序和返回数组的java程序
【发布时间】:2013-02-14 22:18:56
【问题描述】:

所以我正在处理的代码看起来像这样

import java.util.Scanner;
public class ReadStrings{
public static String main(String[] args) {
Scanner in = new Scanner(new File("input3.txt"));
String [] array = new String[100];
int nextSpot = 0;

while( in.hasNext()){
  array[nextSpot++] = in.next();
}
//use the sort function
selectionSort(array, nextSpot);
//print the results

}



public static void selectionSort(String [] array, int nextSpot){
  String tmp;
  for (int i = 0; i < nextSpot; i++) {
    for (int j = i + 1; j < nextSpot; j++) {
      if( array[i].equals(array[j])){
        tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
      }
    }
  }
}
}

假设文本文件存在,我的代码有问题吗? 我也不知道如何打印结果数组

【问题讨论】:

  • 有什么问题?代码有效吗?如果没有,您面临什么问题?你是怎么解决的?
  • 调用selectionSort后不知道怎么打印结果
  • 你可以遍历你的数组,并在你的 main 方法中打印每个元素。顺便说一句,我不知道您的选择排序如何工作。您正在使用equals 方法而不是compareTo

标签: java arrays sorting


【解决方案1】:

您的问题不清楚。我假设您想将结果打印到文件本身。您可以像这样使用BufferedWriter 类:

BufferedWriter writer = new BufferedWriter(new FileWriter(new File("input3.txt")));

并使用它的write() 方法来打印数组。

不过,您可能想检查一下您的 selectionSort()

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多