Java useDelimiter 和 nextLine

标签 java string java.util.scanner delimiter

我正在尝试创建一个程序,使用分隔符分隔字符串输入(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();
    }
}

问题是,您不知道用户何时输入最后一个 token (路径的最后一部分)。

因此,最好将整个输入作为一行读取,然后将其分成几部分。例如:

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数组来逐行输出内容。

关于Java useDelimiter 和 nextLine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60239428/

相关文章:

c - 逐字阅读,包括后面的空格

java - 需要帮助解析 Java 中的字符串

Java - 使用扫描仪读取同一行上的多个项目

java - 扫描器类 NoSuchElementFoundException

java - ZK - 检查元素是否具有焦点

java - 如何用Java重写ModelAndView的集成测试

java - 如何使用 grails 中的现有 java 类

c - 帮我找出错误?

java - 从文本文件中读取整数

java - 等待线程资源消耗