如何使用 Java 中的 Scanner 类从控制台读取输入?
如何使用 Scanner
类从控制台读取输入?像这样:
How could I read input from the console using the Scanner
class? Something like this:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
基本上,我想要的只是让扫描器读取用户名的输入,并将输入分配给 String
变量.
Basically, all I want is have the scanner read an input for the username, and assign the input to a String
variable.
一个简单的例子来说明 java.util.Scanner
的工作原理是从 System.in.真的很简单.
A simple example to illustrate how java.util.Scanner
works would be reading a single integer from System.in
. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
要检索用户名,我可能会使用 sc.nextLine()
.
To retrieve a username I would probably use sc.nextLine()
.
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
您也可以使用 next(String pattern)
如果你想对输入有更多的控制,或者只是验证 username
变量.
You could also use next(String pattern)
if you want more control over the input, or just validate the username
variable.
您可以在 java.util.Scanner