2013-03-18 121 views
0

好,第一次发帖,耶! 现在我知道这个话题已经被打死了。但这里有一个问题:Java的扫描仪+排序

编写一个程序,读取文本文件 空格隔开的单词并以升序显示的话。 (如果两个单词相同,则只显示一个 )。从命令行传递文本文件名。 假设文本文件仅包含由空格分隔的单词。

现在我已经从文件部分阅读想通了。但是,我如何“从命令行传递文件名”?然后是唯一性因素。

帮助?

编辑: 谢谢你们的帮助。下面是我目前的处境:

import java.io.*; 
import java.util.*; 

public class Splittext { 
    public static void main(String[] args) { 
     String fileName = args[0]; 
     Scanner s = null; 

     try { 
      s = new Scanner(new BufferedReader(new FileReader(fileName))); 
       while (s.hasNext()) { 
        System.out.println(s.next()); 
       } 
      } catch (FileNotFoundException fnfe) { 
      System.exit(0); 
     } finally { 
       if (s != null) { 
        s.close(); 
       } 
      } 


     TreeSet<String> ts = new TreeSet<String>(); 

     ts.add(s); 

     Iterator it = ts.iterator(); 

     while(it.hasNext()) { 
      String value = (String)it.next(); 
      System.out.println("Result :" + result); 
     } 
    }   
} 

但这种收益率:为附加(java.util.Scanner中)没有合适的方法;方法java.util.TreeSet.add(java.lang.String)不适用。

对不起,小白的问题!真正内心的感谢各位的帮助:)

+1

'字符串文件名= ARGS [0];' – Reimeus 2013-03-18 19:46:55

+3

@RobHeiser的功课标签已被弃用。请不要使用它。 – 2013-03-18 19:50:32

+0

[命令行参数](http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html)。 [排序](http://stackoverflow.com/questions/740936/how-do-i-sort-records-in-a-text-file-using-java)。 – Dukeling 2013-03-18 19:52:06

回答

3

做这样的。

public static void main(String args[]) { 
    String fileName = args[0]; 
    Scanner s = null; 

    try { 
     s = new Scanner(new BufferedReader(new FileReader(fileName)); 

     while (s.hasNext()) { 
      System.out.println(s.next()); 
     } 
    } finally { 
     if (s != null) { 
      s.close(); 
     } 
    } 
} 

运行这个喜欢

java classname readthisfile.txt 
0

但我怎么 “通过在命令行中的文件名”?

public static void main(String args[]) 
{ 
    final String filename = args[0]; 
    // ... 
} 

再有就是唯一性的因素。

和排序因素。

  1. 将所有单词插入TreeSet
  2. 遍历它并打印值。他们将被排序和独特。
0

您的main函数有String[] args传递给它,当你启动你的应用程序,这是你访问你输入参数的地方。

例如为:

java -cp . my.class.Example Happy Days 

将看到实施例类接收到该:

public static void main(String[] args) { 
    // args.length == 2 
    // args[0] = "Happy" 
    // args[1] = "Days" 
}