有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java忽略字符串

我是编程新手,这个问题总是摆在我面前 当我运行程序时,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();

        }

    }
}

共 (1) 个答案

  1. # 1 楼答案

    您正在提醒这样一个事实,即Scanner#nextLine方法不会使用输入的最后一个换行符,因此在下次调用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();
    
        }
    
    }