2

I'm new to programming and this problem always faces me When I run the program Java ignores a string input inside an if What did I do wrong?

import java.util.Scanner;

public class JavaApplication {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("------ FEEDBACK/COMPLAINT ------\n"
                + "-------------------------------------\n"
                + "| 1: Submit Feedback |\n"
                + "| 2: Submit Complaint |\n"
                + "| 3: Previous Menu |\n"
                + "-----------------------------------\n"
                + "> Please enter the choice: ");
        int feedorcomw = input.nextInt();

        if (feedorcomw == 1) {
            String name;
            System.out.print("> Enter your name (first and last): ");
            name = input.nextLine();
            System.out.println("");
            System.out.print("> Enter your mobile (##-###-####): ");
            int num = input.nextInt();

        }

    }
}
Flexo
  • 82,006
  • 22
  • 174
  • 256
David
  • 37
  • 7
  • what type of the error are you getting? – Andrew Tobilko Apr 09 '16 at 18:48
  • 2
    Maybe this answers your problem http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods – RubioRic Apr 09 '16 at 18:51
  • @and your edit doesn't make much sense - why make a minimal complete example into one that isn't instead of just fixing the formatting? – Flexo May 07 '16 at 18:10

1 Answers1

1

you are ommitting the fact that Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine

try adding a input.nextLine(); after that and everything will work fine

Example:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print("------ FEEDBACK/COMPLAINT ------\n"
            + "-------------------------------------\n"
            + "| 1: Submit Feedback |\n"
            + "| 2: Submit Complaint |\n"
            + "| 3: Previous Menu |\n"
            + "-----------------------------------\n"
            + "> Please enter the choice: ");
    int feedorcomw = input.nextInt();

    input.nextLine();
    if (feedorcomw == 1) {
        String name;
        System.out.print("> Enter your name (first and last): ");
        name = input.nextLine();
        System.out.println("");
        System.out.print("> Enter your mobile (##-###-####): ");
        int num = input.nextInt();

    }

}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83