[英]Java Scanner String input
我正在编写一个使用 Event 类的程序,其中有一个日历实例和一个 String 类型的描述。 创建事件的方法使用 Scanner 来获取月、日、年、小时、分钟和描述。 我遇到的问题是 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();
如果在 nextInt() 方法之后使用 nextLine() 方法,nextInt() 读取整数标记; 因此,该整数输入行的最后一个换行符仍在输入缓冲区中排队,下一个 nextLine() 将读取整数行的其余部分(这是空的)。 所以我们 read 可以读取空的空间到另一个字符串可能工作。 检查下面的代码。
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);
}
}
使用这个在扫描字符串之前清除以前的键盘缓冲区它会解决你的问题scanner.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();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.