[英]Prompt user in command prompt
I'm currently working on a program that takes information form google sheets and runs calculations. 我目前正在开发一个程序,该程序从Google表格获取信息并运行计算。 I use "gradle -q run" to run my program and I want it to prompt the user inside the terminal.
我使用“ gradle -q run”来运行程序,并希望它在终端内提示用户。 Right now I am using scanner but it says "Enter your name: Exception in thread "main" java.util.NoSuchElementException" when I run instead of waiting for me to add a input, How do I fix this?
现在,我正在使用扫描仪,但是在运行时(而不是等待我添加输入),它说“输入您的名称:线程“ main”中的异常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));
}
}
}
Try using 尝试使用
while(scanner.hasNextLine()){
username = scanner.nextline();
}
It worked for me on https://www.compilejava.net/ 它在https://www.compilejava.net/上为我工作
You may also consider using: io.Console 您也可以考虑使用: io.Console
Sample: 样品:
Console console = System.console();
String name = console.readLine("Enter your name: ");
Scanner ageScanner = new Scanner(console.readLine("Enter your age: ");
int age = ageScanner.nextInt();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.