2014-03-05 65 views
-3

我有一个包含50个不同长度和内容的字符串行的文本文件。我需要阅读文件并按升序排序。 排序条件:我如何通过ķ移动到分拣串线:字数在从字母开始的“a”由Shell排序字符串排序

public static void main(String[] args) throws FileNotFoundException { 
    String token1 = ""; 
    Scanner inFile1 = new Scanner(new File("E:\\text.txt")); 

    List<String> temps = new LinkedList<String>(); 
    inFile1.useDelimiter(". "); 

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

    String[] tempsArray = temps.toArray(new String[0]); 
    for (int i = 0; i < tempsArray.length; i++) { 
     System.out.println(tempsArray[i]); 
    } 

    int cnt = 0; //counts of words in the string line 
    for (int i=0; i<tempsArray.length; i++) { 
     int k=0; //counts of words that start from the letter "а" 
     System.out.println("Line № = " + i); 
     StringTokenizer st = new StringTokenizer(tempsArray[i]);   
     while (st.hasMoreTokens()) { 
      cnt++; 
      String s= st.nextToken(); 
      if (s.charAt(0)=='a') {      
       k++;    
      }    
     } 
     System.out.println("Words count = " + cnt); 
     cnt=0; 
     System.out.println("Words 'а' = " + k); 
    }  
} 

新问题了一句多少?该代码后还应该做些什么?

+1

为什么不给它一个尝试第一,看多远,你可以得到的,根据你了解在Java中不同的数据类型是什么?然后,如果你卡住,发布一个问题。 – ProgrammerDan

+0

我不需要编码方面的帮助。我需要帮助完成这项任务的算法。然后我会尝试为该算法编写代码。 – iFlash

回答

1

您可以使用this code进行shell排序,它可以同时使用数字和字符串。首先,您需要将所有字符串存储在数组中。

在我给出的参考文献中,您应该使用类似下面这样的代码来更改主要方法,以从您的文件读取输入并将其存储在数组中。

String token1 = ""; 

// create Scanner inFile1 
Scanner inFile1 = new Scanner(new File("YourFilenNme")); 

List<String> temps = new LinkedList<String>(); 


while (inFile1.hasNext()) { 
    // find next line 
    token1 = inFile1.next(); 
    temps.add(token1); 
} 
inFile1.close(); 

String[] tempsArray = temps.toArray(new String[0]); 

Shell.sort(tempsArray); 
    show(tempsArray); 

编辑:

StringTokenizer st = new StringTokenizer("this is a test"); 
while (st.hasMoreTokens()) { 
    String s= st.nextToken(); 
    if (s.charAt(0)=='a') 
    { 
     "do what you want here" 
    } 

} 
+0

在我编写的代码中,它将每行存储为数组项。编辑部分之后,我展示了如何标记字符串以及如何检查第一个字符是否为'a'。 –

+0

我已经可以看到)谢谢! – iFlash