在命令提示符下提示用户

时间:2016-09-28 16:27:48

标签: java gradle command-prompt

我目前正在开发一个程序,它从谷歌表中获取信息并运行计算。我使用“gradle -q run”来运行我的程序,我想让它在终端内提示用户。现在我正在使用扫描仪,但它说“输入你的名字:线程中的异常”主“java.util.NoSuchElementException”当我运行而不是等待我添加输入时,我该如何解决这个问题?

public static void main(String[] args) throws IOException {
        // Build a new authorized API client service.
        Sheets service = getSheetsService();

        // Prints the names and majors of students in a sample spreadsheet:
        // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
        String spreadsheetId = "1Pfs-EpysJZXibe1pHiPLEx8cOCC86H5he5ouApejqiE";
        String range = "Sheet1!A:E";

     // create a scanner so we can read the command-line input
        Scanner scanner = new Scanner(System.in);

        //  prompt for the user's name
        System.out.print("Enter your name: ");

        // get their input as a String
        String username = scanner.nextLine();

        // prompt for their age
        System.out.print("Enter your age: ");

        // get the age as an int
        int age = scanner.nextInt();

        System.out.println(String.format("%s, your age is %d", username, age));


        ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
        List<List<Object>> values = response.getValues();
        if (values == null || values.size() == 0) {
            System.out.println("No data found.");
        } else {
          System.out.println("Dominik's Awesome Script Says:");
          System.out.println("");
          for (List row : values) {
            // Print columns A and E, which correspond to indices 0 and 4.
            System.out.printf("%s, %s\n", row.get(0), row.get(4));
          }
        }
    }

2 个答案:

答案 0 :(得分:0)

尝试使用

while(scanner.hasNextLine()){
    username = scanner.nextline();
}

https://www.compilejava.net/

对我有用

答案 1 :(得分:0)

您还可以考虑使用:io.Console

示例:

Console console = System.console();
String name = console.readLine("Enter your name: ");
Scanner ageScanner = new Scanner(console.readLine("Enter your age: ");
int age = ageScanner.nextInt();