Java Scanner字符串输入 [英] Java Scanner String input

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

问题描述

我正在编写一个使用Event类的程序,其中包含一个日历实例和一个String类型的描述。创建事件的方法使用扫描程序来获取月,日,年,小时,分钟和描述。我遇到的问题是Scanner.next()方法只返回空格前的第一个单词。因此,如果输入是我的生日,则该事件实例的描述仅为我的。

I'm writing a program that uses an Event class, which has in it an instance of a calendar, and a description of type String. The method to create an event uses a Scanner to take in a month, day, year, hour, minute, and a description. The problem I'm having is that the Scanner.next() method only returns the first word before a space. So if the input is "My Birthday", the description of that instance of an Event is simply "My".

我做了一些研究,发现人们使用了Scanner。 nextLine()针对这个问题,但是当我尝试这个时,它只是跳过输入应该去的地方。以下是我的代码的一部分:

I did some research and found that people used Scanner.nextLine() for this issue, but when I try this, it just skips past where the input should go. Here is what a section of my code looks like:

System.out.print("Please enter the event description: ");
String input = scan.nextLine();
e.setDescription(input);
System.out.println("Event description" + e.description);
e.time.set(year, month-1, day, hour, min);
addEvent(e);
System.out.println("Event: "+ e.time.getTime());    

这是我得到的输出:

Please enter the event description: Event description
Event: Thu Mar 22 11:11:48 EDT 2012

它跳过空格以输入描述字符串,因此,描述(最初设置为空格 - )永远不会更改。

It skips past the space to input the description String, and as a result, the description (which is initially set to a blank space - " "), is never changed.

我该如何解决这个问题?

How can I fix this?

推荐答案

当你读完时使用nextInt()之类的年份日小时分钟,它会在解析器/缓冲区中留下其余部分(即使它是空白的),所以当你调用nextLine()时,你正在读取第一行的其余部分。

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

我建议您在打印下一个提示之前调用scan.nextLine()来丢弃剩下的行。

I suggest you call scan.nextLine() before you print your next prompt to discard the rest of the line.

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

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