获取键盘输入 [英] Getting Keyboard Input

查看:167
本文介绍了获取键盘输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java的控制台中从用户获取简单的键盘输入(整数)?我使用 java.io。* 的东西实现了这一点,但它说它已被弃用。



解决方案

您可以使用 Scanner



首先导入:

  import java.util.Scanner; 

然后你这样使用。

 扫描仪键盘=新扫描仪(System.in); 
System.out.println(enter an integer);
int myint = keyboard.nextInt();

注意:如果您使用 nextInt() nextLine()你可能会有一些麻烦,因为 nextInt()不会读取最后一个换行符输入,所以 nextLine()然后不会被执行所需的行为。请参阅上一个问题中的解决方法跳过nextLine使用nextInt 。 p>

How do I get simple keyboard input (an integer) from the user in the console in Java? I accomplished this using the java.io.* stuff, but it says it is deprecated.

How should I do it now?

解决方案

You can use Scanner class

Import first :

import java.util.Scanner;

Then you use like this.

Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

Side note : If you are using nextInt() with nextLine() you probably could have some trouble cause nextInt() does not read the last newline character of input and so nextLine() then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping nextLine using nextInt.

这篇关于获取键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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