在方法

时间:2016-10-08 16:23:56

标签: java arrays methods while-loop stringtokenizer

我试图保持我的数组的值来自Unsorted方法,以便它可以用于在单独的方法中使用另一个返回值,即Sorted方法。我知道这没有问题,但是当运行程序(使用GUI完成)时,Unsorted方法之外的数组只有1个项目,实际上会丢失除了其中一个项目之外的所有项目。

我有理由相信这是因为行

while((line = myFile.readLine()) != null){ ...

因为当我尝试在Sorted函数中输出while循环之外的数组项时,它也只返回数组的最后一项。这里没有理由使用split.string,因为我知道Tokenizer可以轻松完成工作,项目要求使用Tokenizer。我可以想象我可以改变令牌添加到数组的方式,但是我已经尝试了添加函数,但它没有用,当这样做时,我得到“方法add(String)未定义类型字符串”

以下是示例文本文件(dates.txt):

20161001
20080912,20131120,19980927
20020202,hello
20120104

这些日期的结构为“yearmonthday”,长度均为8.添加了hello以确保我们检查文本文件中的相应项目。

以下是代码:

    import java.util.StringTokenizer;

public class Project1{
    public static TextFileInput myFile;
    public static StringTokenizer myTokens;
    public static String[] dates;
    public static String line;
    public String Unsorted(String date) {
    myFile = new TextFileInput("dates.txt");
    while((line = myFile.readLine()) != null){
        myTokens = new StringTokenizer(line,",");
        dates = new String[myTokens.countTokens()];

        int i=0;
        while (myTokens.hasMoreTokens()) {
            dates[i]=myTokens.nextToken();
            i++;
        }
        // prints any items that are not 8 chars long
        for (int j = 0; j < dates.length; j++){
            if (dates[j].length() < 8){
                System.out.println(dates[j]);
            }
        }
        // I changed the date += String.valueof.dates[i] + "/n"
        // to System.out.println
        for (int n = 0; n < dates.length; n++){
            if (dates[n].length() == 8){
                System.out.println(dates[n]);
            }
        }   
    }
    return date;
}
// I changed the datesort += String.valueof.dates[i] + "/n"
// to System.out.println
public String Sorted(String datesort){
    selectionSort(dates, dates.length);
    for (int i = 0; i < dates.length; i++){
        if (dates[i].length() == 8){
            System.out.println(dates[i]);
        }
    }
    return datesort;
}

private static void selectionSort(String array[], int length) { 
      for ( int i = 0; i < length - 1; i++ ) { 
         int indexLowest = i; 
         for ( int j = i + 1; j < length; j++ ) 
            if ( array[j].compareTo(array[indexLowest]) < 0) 
               indexLowest = j;
         if ( array[indexLowest] != array[i] ) { 
            String temp = array[indexLowest];
            array[indexLowest] = array[i]; 
            array[i] = temp; 
         }  
      } 
   } 
}

该计划的目的是:

hello
20161001
20080912
20131120
19980927
20020202
20120104
20120104

但它应该是:

hello
20161001
20080912
20131120
19980927
20020202
20120104
19980927
20020202
20080912
20120104
20131120
20161001
提前谢谢,如果我不清楚,我道歉。

0 个答案:

没有答案