Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is line 17 of this Java program not being executed?
    text
    copied!<p>As an exercise for my Java course in Uni this morning, I had to write a small program to ask the user to input some details, then print them back. I've since finished writing it, but I ran into a strange problem along the way.</p> <p>See the code below:</p> <pre><code>import java.util.Scanner; public class Scanner_Exercise { public static void main (String[] args) { Scanner keyboardIn = new Scanner(System.in); int accountId; String accountName; float accountBalance; System.out.println("Account ID: "); //Line 13 accountId = keyboardIn.nextInt(); //Line 14 System.out.println("Account name: "); //Line 16 accountName = keyboardIn.nextLine(); //Line 17 System.out.println("Account balance: "); accountBalance = keyboardIn.nextFloat(); } } </code></pre> <p>When this program runs, line 17 (refer to comments) is skipped; <code>Account name:</code> is printed, but the user is not given the opportunity to enter the information, as if that line of code was commented out. No errors are thrown. The output looks like this:</p> <blockquote> <p>Account ID:<br> 2<br> Account name:<br> Account balance:</p> </blockquote> <p>However, if I switch lines 13 and 14 with 16 and 17, like as follows, the program runs fine, and no lines are skipped.</p> <pre><code>System.out.println("Account name: "); //Line 16 accountName = keyboardIn.nextLine(); //Line 17 System.out.println("Account ID: "); //Line 13 accountId = keyboardIn.nextInt(); //Line 14 </code></pre> <p>Why is the line 17 being skipped in the first case, but not the second?</p> <p>If it's somehow relevant, I am using JDK 6 Update 18, and TextPad 5.3.1.</p>
 

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