Java忽略字符串

标签 java string input

我是编程新手,这个问题一直困扰着我 当我运行程序时,Java 会忽略 if 中的字符串输入 我做错了什么?

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();

        }

    }
}

最佳答案

您忽略了 Scanner#nextInt 方法不会消耗您输入的最后一个换行符这一事实,因此在下一次调用 Scanner#nextLine

尝试添加 input.nextLine();之后一切都会正常进行

示例:

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();

    }

}

关于Java忽略字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521153/

相关文章:

java - 如何使用 jstack 查找阻塞线程

Ruby 解析字符串

java - BufferedWriter 没有在文件中为添加了 "\n"的字符串写入新行

java - 如何编写当用户仅按 Enter 时执行的方法?

java - 如何在另一个类中调用 ListView 然后清除它

java - 如何从 X509 证书中提取 AuthorityKeyIdentifier

python - Pandas 过滤串联的多个子字符串

python - 使用读取的新值更新列表值 - Python

javascript - 如何在JS中删除存储在数组中的输入

java - 并排打印一维和二维阵列