有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java扫描器字符串输入

我正在编写一个程序,它使用一个事件类,其中包含一个日历实例和一个String类型的描述。创建事件的方法使用扫描仪获取月、日、年、小时、分钟和描述。我遇到的问题是扫描仪。方法只返回空格前的第一个单词。因此,如果输入是“我的生日”,那么事件实例的描述就是“我的生日”

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

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

我怎样才能解决这个问题


共 (5) 个答案

  1. # 1 楼答案

    在扫描字符串之前,使用此选项清除上一个键盘缓冲区 它会解决你的问题 扫描仪。nextLine()//这是为了清除键盘缓冲区

  2. # 2 楼答案

    当您使用诸如nextInt()之类的内容读取年-月-日-小时-分钟时,它会将该行的其余部分保留在解析器/缓冲区中(即使该行为空),因此当您调用nextLine()时,您正在读取第一行的其余部分

    我建议你叫扫描。打印下一个提示以放弃行的其余部分之前,请执行nextLine()

  3. # 3 楼答案

    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);
        }
    }
    
  4. # 4 楼答案

    如果紧跟在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);
        }
    }
    
  5. # 5 楼答案

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