Java扫描器字符串输入

20
我正在编写一个使用Event类的程序,其中包含一个日历实例和一个类型为String的描述。创建事件的方法使用Scanner获取月份、日期、年份、小时、分钟和描述。我的问题在于Scanner.next()方法只返回空格之前的第一个单词,因此如果输入是"My Birthday",那么该事件实例的描述只会是"My"。
我做了一些研究,并发现人们用Scanner.nextLine()解决这个问题,但当我尝试时,它跳过了应该输入的位置。下面是我的代码片段:
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
它跳过了输入描述字符串的空格,因此描述(最初设置为空格 -“”)从未更改。如何修复?

你根本没有打印描述,那你怎么知道它读取不正确呢? - Michael Myers
你能提供一个输入示例吗? - Michael
我不小心省略了打印描述的代码行,但我现在已经加上了。@Michael,我不知道该如何告诉您有关输入示例的信息,因为我从未收到输入描述的提示。 - HolidayTrousers
你是如何输入时间信息的? - Michael
5个回答

24

当您使用类似nextInt()的函数读取年月日时分时,它会将该行的剩余部分留在解析器/缓冲区中(即使它为空),因此当您调用nextLine()函数时,您会读取第一行的其余部分。

我建议在打印下一个提示之前调用scan.nextLine()函数以丢弃该行的其余部分。


我也遇到了同样的麻烦。我在input.nextLine();的位置添加了scan.nextLine();,但是它给我一个警告,说找不到符号scan,需要创建scan类。 - Zachary Dale
@ZacharyDale 你只能使用你已经定义的变量。使用你已经定义的扫描器。 - Peter Lawrey
@PeterLawrey 这是我的问题 http://stackoverflow.com/questions/41882552/two-steps-running-at-once-in-java?noredirect=1#comment70947891_41882552 - Zachary Dale
@ZacharyDale 你需要使用 nextLine() 来消耗单词或数字后面剩余的行,即使你期望它是空的。然后你需要再次调用 nextLine() 来获取下一行。 - Peter Lawrey

2
    Scanner ss = new Scanner(System.in);
    System.out.print("Enter the your Name : ");
    // Below Statement used for getting String including sentence
    String s = ss.nextLine(); 
   // Below Statement used for return the first word in the sentence
    String s = ss.next();

2
如果在nextInt()方法之后立即使用nextLine()方法,则nextInt()会读取整数标记。因此,该行整数输入的最后一个换行符仍在输入缓冲区中排队,下一个nextLine()将读取整数行的剩余部分(为空)。因此,我们可以尝试将空格读入另一个字符串。请查看以下代码。
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int i = scan.nextInt();
        Double d = scan.nextDouble();
        String f = scan.nextLine();
        String s = scan.nextLine();


        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
         System.out.println("Int: " + i);
    }
}

1
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int i = scan.nextInt();
        Double d = scan.nextDouble();
        scan.nextLine();
        String s = scan.nextLine();
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

0

在扫描字符串之前使用此方法清除先前的键盘缓冲区,它将解决您的问题。 scanner.nextLine(); // 这是用来清除键盘缓冲区的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接