Java扫描程序对象跳过行?

时间:2016-02-07 23:54:55

标签: java java.util.scanner

所以它已经有一段时间了,因为我已经真正编写了基于java的控制台,

我在下面有这个方法,应该问我每一行,对吧?相反,我得到一个提示,然后是三个。我做错了什么?

        try {

        System.out.println("Please enter the product's LONG details: ");
        product.setLongDetails(sc.next()); //set products long details

        System.out.println("Please enter the product's SHORT details: ");
        product.setShortDetails(sc.next()); //set short details

        System.out.println("Please enter the product's UPC data: ");
        product.setUpc(sc.next()); //set upc

        System.out.println("Please enter the product's stock: ");
        product.setStock(sc.nextInt());

        System.out.println("Please enter the products price. ");
        System.out.println("This MUST be entered with no dollar sign.");
        product.setPrice(sc.nextBigDecimal());

        InventoryManager.addProduct(product); //add product to database

    }

我的控制台输出如下:

Please enter the product's LONG details: 
Fireplace Cleaning Package
Please enter the product's SHORT details: 
Please enter the product's UPC data: 
Please enter the product's stock: 
BUILD STOPPED (total time: 3 minutes 5 seconds)

扫描程序在类声明中初始化为:

public static Scanner sc = new Scanner(System.in); //class level scanner object for reuse.

如果我在每个对象集方法之间调用sc.nextLine(),它会正确提示但是会得到错误的信息:

Please enter the product's SHORT details: 
Fire Poker

将对象显示为: 请输入您的选择:     Fire

2 个答案:

答案 0 :(得分:1)

documentation州:

  

扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格。

这意味着当您输入带空格的文本时(例如" Fireplace Cleaning Package"在您的示例中),它会分成3个不同的输入,每个输入都会被sc.next()的一次调用返回

解决方案是将分隔线模式调整为换行符:

sc.useDelimeter("\\r?\\n");

答案 1 :(得分:0)

Scanner.next()接受下一个完整标记,后跟doumentation中描述的分隔符。由于您输入三个单词(此处的分隔符是空格),前三个

sc.next()

将阅读每个单词。我认为你要找的是

sc.nextLine()