Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In your <code>do while</code> loop, you don't want the <code>nextLine()</code>, you just want <code>next()</code>.</p> <p>So change this:</p> <pre><code>answer = input.nextLine(); </code></pre> <p>to this:</p> <pre><code>answer = input.next(); </code></pre> <p>Note, as others have suggested, you could convert this to a <code>while</code> loop. The reason for this is that <code>do while</code> loops are used when you need to execute a loop at least once, but you don't know how often you need to execute it. Whilst it's certainly doable in this case, something like this would suffice:</p> <pre><code>System.out.println("Do you want to play again? (Y/N) "); answer = input.next(); while (!answer.equalsIgnoreCase("y") &amp;&amp; !answer.equalsIgnoreCase("n")) { System.out.println("That is not valid input. Please enter again"); answer = input.next(); } if (answer.equalsIgnoreCase("n")) keepPlaying = false; </code></pre> <p>The <code>while</code> loop keeps looping as long as "y" or "n" (ignoring case) isn't entered. As soon as it is, the loop ends. The <code>if</code> conditional changes the keepPlaying value if necessary, otherwise nothing happens and your outer <code>while</code> loop executes again (thus restarting the program).</p> <p><strong>Edit: This explains WHY your original code didn't work</strong></p> <p>I should add, the reason your original statement didn't work was because of your first <code>do while</code> loop. In it, you use:</p> <pre><code>guess = input.nextInt(); </code></pre> <p>This reads the number off the line, but not the return of the line, meaning when you use:</p> <pre><code>answer = input.nextLine(); </code></pre> <p>It immediately detects the leftover carriage from the <code>nextInt()</code> statement. If you don't want to use my solution of reading just <code>next()</code> you could swallow that leftover by doing this:</p> <pre><code>guess = input.nextInt(); input.nextLine(); rest of code as normal... </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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