java - java - 如何在Java中以空格分隔用户输入
问题描述
System.out.print("Enter an integer width and height between 2 and 25: ");
String[] str = sc.next().split(" ");
System.out.print(str.length);
我想接受用空格分隔的用户输入,但它只接受第一个输入。
解决方案
您应该使用sc.nextLine()而不是 sc.next ()。
根据 javadoc,sc.next()
Finds and returns the next complete token from this scanner.
sc.next()将返回第一个“令牌”(在您的情况下为 10,因为您的输入被 10 到 20 之间的“空格”标记)。
因此,您的代码应如下所示,符合您的期望:
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer width and height between 2 and 25: ");
String[] str = sc.nextLine().split(" ");
System.out.print(str.length);
sc.close();