Vswe's Summer Courses | You're not logged in. Sign up or log in | Server time: | Donate
One can now see other persons' badge hunts. Simply head over to their profiles to access them.

Go back to sub forum page

General forum

Non-course related subjects

3. Programming help

Problem with nextLine();

  • 2014-02-09 13:42:31
    import java.util.Scanner;

    public class Menu {
    void startMenu() {
    int select = 0;
    String name;
    int number;
    boolean family;
    String temp;
    Scanner sc = new Scanner(System.in);

    System.out.println("Welcome to the person archive.");
    System.out.println("Please select what to do.");
    System.out.printf("1. Show all.\n2. Show specifik.\n3. Add.\n4. Delete.\n\n");

    select = sc.nextInt();

    if (select == 1) {
    System.out.println("You have selected nr. 1");
    } else if (select == 2) {
    System.out.println("You have selected nr. 2");
    } else if (select == 3) {
    System.out.println("Please enter who you want to add.");
    temp = sc.nextLine();// seem to need this to make it work or else it jumps over the name = sc.nextLine();
    name = sc.nextLine();
    number = sc.nextInt();
    System.out.println("Family? true/false");
    family = sc.nextBoolean();
    System.out.println(name + " " + number + " " + family);
    } else if (select == 4) {
    System.out.println("You have selected nr. 4");
    } else {

    If i delete the temp = sc.nextLine(); it seems to just past the name = sc.nextLine(); why is that?
  • 2014-02-09 22:31:22
    Hello themaniacz,

    nextInt() doesn't finish the line it reads from. When you use nextLine() it reads everything until the end of the line and goes to a new line. So if the line isn't finished when you ask for the content of the rest of the line it passes the remainder(Which is probably empty).
    You can check this by commenting temp=etc. and entering "3 John" for example that will automatically pick option 3 and enter "John" as the name.
    You need nextLine() to clear the line, so Java uses new user input.

    However you don't need Temp=sc.nextLine() a simple sc.nextLine() suffices because you probably don't need the value of temp.

    I hope I have been clear enough and that this was useful.
    If you have any further questions please keep asking them.

  • Log in or sign up to reply to this thread