首页 > 解决方案 > Console.getLine 和 Console.getString 不接受所有用户输入 - JAVA

问题描述

我正在尝试接受用户输入(国家名称)以添加到我显示的国家列表中。但是,它不允许我输入超过 8 个字符的国家/地区名称。例如,当我输入“Venezuela”时,输出是“Venezuel”,当我输入“United States”时,输出是“United S”。下面是我用来接受用户输入的方法。我已经尝试过 Console.getString 和 Console.getLine ,但都不能接受超过 8 个字符。

 public static void addCountry() {
    String name = Console.getString("Enter country name: ");

    Country country = new Country();
    country.setName(name);
    countryDAO.add(country);

    System.out.println();
    System.out.println(name
            + " has been added.\n");
}

我在 Console 类中也有这些方法

import java.util.Scanner;

public class Console {

private static Scanner sc = new Scanner(System.in);

public static String getLine(String prompt) {
    System.out.print(prompt);
    String s = sc.nextLine();        
    return s;
}

public static String getString(String prompt) {
    System.out.print(prompt);
    String s = sc.next();        
    sc.nextLine();               
    return s;
}
}

标签: java

解决方案


使用它来获取输入而不是 sc.next():

String s = sc.nextLine();

并删除您添加 sc.nextLine() 的下一行

希望有帮助!


推荐阅读