如何验证 Scanner 类中的下一个标记是否为空以区分循环条件?

问题描述 投票:0回答:2

我正在尝试解决教授给我们的问题。我需要对文件

data.txt
进行排序,方法是在
;
的出现处附加空格,在
;;
的出现处附加新行。我在确定 while 循环中的 else if 子句的语法时遇到问题。

Data.txt contains the following 2 lines:

约翰;88;卡尔;;贾夫
海伦;玛丽;;123;99

The current code is as follows:

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

class Delimit {
    public static void main(String[] args) throws IOException {
        // Initiates new FileInputStream to read text document
        File f = new File("data.txt");
        // Initiates new Scanner to parse the file, and delimit at ";"
        Scanner s = new Scanner(f).useDelimiter(";");

        // Parses through each token
        while (s.hasNext()) {
            // 
            if (s.hasNext()) {
                // Prints next token followed by a space
                System.out.print(s.next() + " ");
            }
            // else if (next token is empty) {
                // Prints next token followed by a new line
                System.out.print(s.next() + "\n");
            }
        }
        s.close(); // Closes the Scanner
    }
}

如果有更好的定界和替换方法,请赐教!我一直在努力提高我对正则表达式和字符串定界的掌握。谢谢!

java java.util.scanner delimiter
2个回答
2
投票

就个人而言,我会取消使用定界符,只做一个简单的替换,

;;
->
\n
然后
;
->
; 

 Scanner s = new Scanner(f);
 String line = s.nextLine ();
 while (line != null) {
    s.o.p (line.replace(";;", "\n").replace(";", "; "));
    line = s.nextLine ();
}

1
投票
public static void main(String... args) throws FileNotFoundException {
    try (Scanner scan = new Scanner(new File("data.txt"))) {
        scan.useDelimiter("[;\r]"); // \r as line separator in the file under Windows
        boolean addSpace = false;

        while (scan.hasNext()) {
            String str = scan.next().trim();

            if (str.isEmpty()) {
                System.out.println();
                addSpace = false;
            } else {
                if (addSpace)
                    System.out.print(' ');

                addSpace = true;
                System.out.print(str);
            }
        }
    }
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.