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

查看:141
本文介绍了如何使用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(字符串模式) 如果你想要更多地控制输入,或者只是验证用户名变量。

你会发现有关<* c的 API文档中的实现的更多信息$ c> java.util.Scanner

You'll find more information on their implementation in the API Documentation for java.util.Scanner

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

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