java.util.scanner - Java scanner object skipping lines? -
so been awhile since i've written console based java,
i have method, below, should asking me each line, right? instead, 1 prompt, three.. did wrong herer?
try { system.out.println("please enter product's long details: "); product.setlongdetails(sc.next()); //set products long details system.out.println("please enter product's short details: "); product.setshortdetails(sc.next()); //set short details system.out.println("please enter product's upc data: "); product.setupc(sc.next()); //set upc system.out.println("please enter product's stock: "); product.setstock(sc.nextint()); system.out.println("please enter products price. "); system.out.println("this must entered no dollar sign."); product.setprice(sc.nextbigdecimal()); inventorymanager.addproduct(product); //add product database }
my console outputting this:
please enter product's long details: fireplace cleaning package please enter product's short details: please enter product's upc data: please enter product's stock: build stopped (total time: 3 minutes 5 seconds)
the scanner initialized inside class declaration as:
public static scanner sc = new scanner(system.in); //class level scanner object reuse.
if call sc.nextline() between each objects set method, prompts correctly gets wrong information:
please enter product's short details: fire poker
displays object as: please enter selection: fire
the documentation states:
a scanner breaks input tokens using delimiter pattern, default matches whitespace.
that means when entering text spaces (like "fireplace cleaning package" in example) gets split 3 different inputs, each returned 1 call of sc.next()
.
the solution adjust delimeter pattern newline:
sc.usedelimeter("\\r?\\n");
Comments
Post a Comment