我正在尝试创建一个使用定界符分隔字符串输入(Windows路径)的程序。但是我的程序似乎忽略了定界符。
我期望的结果:
Skriv in sökvägen: C://Windows/System/
C
Windows
System
我得到的结果:
Skriv in sökvägen: C://Windows/System/
C://Windows/System/
以下代码中我缺少什么?
import java.util.Scanner;
public class Sokvagen
{
public static void main(String[] args)
{
//String representing pathway
String sokvag;
//Creating scanner object for reading from input stream
Scanner userInput = new Scanner(System.in);
// Set delimiter to ':' or '/' or whitespace
userInput.useDelimiter("[:/\\s]+");
// Instructions to the user to type a windows patway ex: C://Windows/System/
System.out.print("Skriv in sökvägen: ");
//Input
sokvag = userInput.nextLine();
//Print the result
System.out.println(sokvag);
userInput.close();
}
}
userInput.nextLine()
总是返回整行,而userInput.next()
则使用定界符返回标记。但是然后您需要逐个标记地读取循环标记中的输入,直到...
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws Exception
{
String sokvag;
//Creating scanner object for reading from input stream
Scanner userInput = new Scanner(System.in);
// Set delimiter to ':' or '/' or whitespace
userInput.useDelimiter("[:/\\s]+");
// Instructions to the user to type a windows patway ex: C://Windows/System/
System.out.print("Skriv in sökvägen: ");
do
{
//Input
sokvag = userInput.next();
//Print the result
System.out.println(sokvag);
}
while (????);
userInput.close();
}
}
问题是,您不知道用户何时输入了最后一个令牌(路径的最后一部分)。
因此最好将整个输入读为一行,然后将其分成几部分。例如:
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws Exception
{
String sokvag;
//Creating scanner object for reading from input stream
Scanner userInput = new Scanner(System.in);
// Instructions to the user to type a windows patway ex: C://Windows/System/
System.out.print("Skriv in sökvägen: ");
//Input
sokvag = userInput.nextLine();
String[] parts = sokvag.split("[:/\\s]+");
//Print the result
System.out.println(Arrays.toString(parts));
userInput.close();
}
}
当然,您也可以遍历parts-array以逐行输出内容。