0

我是 Java 新手,正在寻找有关 Java 的 Scanner 类的帮助。下面是问题。我有一个包含多行的文本文件,每行有多对数字。这样每对数字都表示为(数字,数字)。例如 3,3 6,4 7,9。所有这些多对数字都由空格隔开。以下是来自文本文件的示例。

1 2,3 3,2 4,5

2 1,3 4,2 6,13

3 1,2 4,2 5,5

我想要的是我可以分别检索每个数字。这样我就可以创建一个链表数组了。以下是我到目前为止所取得的成就。

Scanner sc = new Scanner(new File("a.txt"));
    Scanner lineSc;
    String line;
    Integer vertix = 0;
    Integer length = 0;
    sc.useDelimiter("\\n"); // For line feeds

    while (sc.hasNextLine()) {
        line = sc.nextLine();
        lineSc = new Scanner(line);

        lineSc.useDelimiter("\\s"); // For Whitespace
        // What should i do here. How should i scan through considering the whitespace and comma
        }

谢谢

4

4 回答 4

1

考虑使用正则表达式,不符合您期望的数据将被轻松识别和处理。

CharSequence inputStr = "2 1,3 4,2 6,13";    
String patternStr = "(\\d)\\s+(\\d),";    
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);

while (matcher.find()) {
    // Get all groups for this match
    for (int i=0; i<=matcher.groupCount(); i++) {
        String groupStr = matcher.group(i);
    }
}

第一组和第二组将分别对应每对中的第一个和第二个数字。

于 2012-07-22T12:16:37.920 回答
0

1.使用nextLine()扫描仪的方法从文件中获取每一整行文本

2.然后使用BreakIteratorclass的静态方法getCharacterInstance(),获取单个字符,它会自动处理逗号、空格等。

3. BreakIterator还给你许多灵活的方法来分离句子、单词等。

有关更多详细信息,请参见:

http://docs.oracle.com/javase/6/docs/api/java/text/BreakIterator.html

于 2012-07-22T12:18:42.540 回答
0

使用 StringTokenizer 类。http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html

//this is in the while loop
//read each line
String line=sc.nextLine();

//create StringTokenizer, parsing with space and comma
StringTokenizer st1 = new StringTokenizer(line," ,");

然后,当您像这样调用 nextToken() 时,每个数字都被读取为字符串,如果您想要该行中的所有数字

while(st1.hasMoreTokens())
{
    String temp=st1.nextToken();

    //now if you want it as an integer
    int digit=Integer.parseInt(temp);

    //now you have the digit! insert it into the linkedlist or wherever you want
}

希望这可以帮助!

于 2012-07-22T17:15:26.757 回答
0

使用 split(regex),更简单:

 while (sc.hasNextLine()) {
      final String[] line = sc.nextLine().split(" |,");
      // What should i do here. How should i scan through considering the whitespace and comma
      for(int num : line) { 
            // Do your job
      }        
 }
于 2012-07-23T06:36:45.520 回答