Java Scanner字符串输入

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

我做了一些研究,发现人们使用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 

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

我怎样才能解决这个问题?

当您使用nextInt()读取年月日时分钟时,它会在解析器/缓冲区中留下其余部分(即使它是空白的),因此当您调用nextLine()时,您正在读取第一行的其余部分。

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

当您使用nextInt()读取年月日时分钟时,它会在解析器/缓冲区中留下其余部分(即使它是空白的),因此当您调用nextLine()您正在读取第一行的其余部分。

我建议你使用scan.next()而不是scan.nextLine()

  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();