我是java的新手,我正在尝试创建一个使用分隔符解析字符串的简单程序。但是每当我尝试这样做而不是打印这样的行:
Hello World
I am Bob
how are you
它会在各自的行上单独打印出每个字符。这是我的代码:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String args[]){
String s = "Hello World|I am bob|how are you ";
Scanner scan = new Scanner(s);
scan.useDelimiter("|");
System.out.println(scan.next());
while (scan.hasNext()){
System.out.println(scan.next());
}
}
}
任何帮助都是apreciated
答案 0 :(得分:2)
请使用不同的分隔符,因为PIPE具有需要转义的特殊字符。
如果严格需要PIPE符号,请尝试
scan.useDelimiter("\\|");
答案 1 :(得分:1)
正如Pm 77-1所说,你必须逃脱管道角色:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String args[]){
String s = "Hello World|I am bob|how are you ";
Scanner scan = new Scanner(s);
scan.useDelimiter("\\|");
System.out.println(scan.next());
while (scan.hasNext()){
System.out.println(scan.next());
}
}
}