如果用户不输入任何内容而仅按Enter键,如何获得响应的代码?

时间:2020-09-01 18:03:35

标签: java

我希望我的代码在用户仅按Enter且不键入其他任何内容时作出响应。我使用.trim仅对放置空格作出反应,但是当我按Enter键作为输入时,它给我一个错误。这是我到目前为止的内容:


import java.util.Scanner;

class Main {

    static Scanner name = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("What is your first name?");
        String a = name.nextLine();
        String b = a.substring(0, 1).toUpperCase() + a.substring(1);
        String c = a.trim();
        if (c.length() != 0) {
            if (a.contains(" ")) {
                System.out.println("You put space in your name. : (");
            } else {
                System.out.println(b + " is a nice name! : )");
            }
        } else {
            System.out.println("Thats not a name! : (");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

try (Scanner scan = new Scanner(System.in)) {
    System.out.println("What is your first name?");

    String str = scan.nextLine().trim();

    if (str.isEmpty())
        System.err.println("You entered an empty name");
    else if (str.contains(" "))
        System.err.println("You put space in your name.");
    else {
        String name = Character.toUpperCase(str.charAt(0)) + str.substring(1);
        System.out.println('\'' + name + "' is a nice name!");
    }
}

答案 1 :(得分:0)

我认为这可能是您想要的。此外,我还重点介绍了一些最佳做法。

class Main {

    private static Scanner scanner = new Scanner(System.in); // Point 0 - Use access modifiers!

    public static void main(String[] args) {

        System.out.println("What is your first name?");
        String name = ""; // Point 1 - Initialize your variables to avoid NullPointerException

        // Point 2 - Always check if there is something to read from scanner
        if (scanner.hasNextLine()) {
            name = scanner.nextLine();
        }

        // Point 3 - You can methods in place instead of stack variables
        if (!name.isEmpty()) {
            if(name.contains(" ")) {
                System.out.println("You put space in your name. : (");
            } else {
                // Point 4 - You can do away with extra variables
                System.out.println(capitalize(name) + " is a nice name! : )");
            }
        } else {
            System.out.println("That's not a name! : (");
        }

        scanner.close(); // Point 5 - Clean up your resources
    }

    // Point 6 - Concise methods makes code more readable
    private static String capitalize(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
}

您可以查找有关Scanner的更多信息。