如何使用 Java 中的 Scanner 类从控制台读取输入? [英] How can I read input from the console using the Scanner class in Java?

查看:31
本文介绍了如何使用 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

这篇关于如何使用 Java 中的 Scanner 类从控制台读取输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆