用于不同类型输入的不同Java扫描仪 [英] Different Java Scanner for input of different types

查看:39
本文介绍了用于不同类型输入的不同Java扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下以下扫描: 我有一个程序要求输入整数,然后输入字符串.

Imagine the following scanario: I have a program which ask for an integer input, followed by a String input.

int age=0;
String name;
Scanner sc = new Scanner(System.in);

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");
name= sc.nextLine();

使用aobe代码时,我没有机会输入名称.所以通常我将声明2个扫描器对象,如下所示:

With the aobe codes, I was not given a chance to enter the name. So normally I will declare 2 scanner objects as follows:

int age=0;
String name;
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);    //2nd Scanner object

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");
name= sc2.nextLine();                    //Using 2nd Scanner Object

我的问题是:是否需要声明多个扫描程序对象以接受不同类型的输入?我是否按照正常的方式行事?

My question is: Is it necessary to declare multiple scanner objects to accept inputs of different types?? Am I doing the proper way as aobve?

多年以来,我一直在考虑这个问题. (SO中的几个问题提到了多个扫描仪,但是他们的问题仅使用一个扫描仪对象,所以我今天要问这个问题.)

I have this question in mind for years already. (Several questions in SO mention multiple scanner, but their questions only used one scanner object, so I am asking this today.)

推荐答案

@skiwi仅使用一个Scanner是正确的,因此您正在正确地做到这一点.它不起作用的原因是nextInt()消耗了组成整数的所有字符,但它没有碰到行尾字符.因此,当调用nextLine()时,它会看到在行尾字符之前没有字符,因此它认为输入了空行,并且返回了空String.但是,nextLine()确实消耗了行尾字符,因此,如果在执行name = sc.nextLine();之前调用一次sc.nextLine();,它应该可以工作.

@skiwi is right about only using one Scanner, so you're doing that right. The reason it doesn't work is that nextInt() consumes all characters that make up the integer, but it does not touch the end-of-line character. So when nextLine() is called, it sees that there are no characters before the end-of-line character, so it thinks that an empty line was entered, and you get an empty String back. However, nextLine() does consume the end-of-line character, so if you call sc.nextLine(); once before you do name = sc.nextLine();, it should work.

这篇关于用于不同类型输入的不同Java扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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