Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think the real problem is that you have some obfuscation in your loop structure that makes it hard to understand the in and out conditions of the scanner with each iteration of the loop. </p> <p>Heres what is really happening. We enter the loop with one token in the Scanner which is not a double. We ask is there a double next in the scanner with <code>hasNextDouble()</code>, which since the one token can not be converted to a double, this returns false. We report an error and <code>isValid</code> remains false. After the branch we call <code>scanner.next()</code> and consumer our non double token. We renter the loop since isValid remains false. We again ask if there is a double next in the Scanner. Now the scanner is empty, since we consumed out token, and this call returns <code>false</code>, so we report another error. Now we call <code>scanner.next()</code> again. Since the scanner is now empty, and scanner.next() implements synchronous message passing (I/O), we now block until the scanner recieves a new token, so your program will stall until you input a new token. Try puting in more into your console. You would probably repeat the loop and see another error. </p> <p>What you want to accomplish is with each loop, consume a token. If that token is a double, accept the input and continue, if not report an error and repeat. Try something like this instead, it should present a more clear picture of what the scanner is doing every loop. </p> <pre><code>public class Calculator { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String customerType = null; System.out.print("Customer Type? (C/R) "); customerType = scan.next(); Double test = null; do{ try{ test = scan.nextDouble(); }catch (InputMismatchException ime){ //will be thrown if the token we input is not a double System.err.println("Error Message"); } }while(test == null); } } </code></pre> <p>Notice i use the wrapper class <code>Double</code> not the primative <code>double</code>. This is so that I can set the double to null, since <code>Double</code> is an <code>Object</code> and not a primitive. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload