gpt4 book ai didi

java - 使用了扫描仪方法,但键盘输入未显示在命令窗口中

转载 作者:行者123 更新时间:2023-12-02 04:02:31 25 4
gpt4 key购买 nike

我在代码中找不到错误。当我移动命令并连续要求两个字符串输入时,它会起作用,但是当我要求一个字符串,然后一个整数,然后再次一个字符串时,我从键盘上没有得到第二个字符串的响应。

我已经剪切并粘贴了 String option = scan.nextLine();到不同的地点。它在整数输入之前起作用,但在之后不起作用。我在命令窗口中看到提示输入用户输入,但是当我按下键盘上的按键时没有任何反应

import java.util.Scanner;

public class Assignment6 {

public static void main(String[] args) {

// Create scanner
Scanner scan = new Scanner(System.in);

// variables
int year;
int numQuestions;
String name;


// Create Geek
System.out.println("Please enter the geeks name: ");
name = scan.nextLine();

System.out.println("Please enter the number of questions the geek answers: ");
numQuestions = scan.nextInt();

System.out.println("\nPlease enter a command or type: ");
String option = scan.nextLine();

}

}

使用eclipse和java

最佳答案

Scanner 类中的 nextInt() 方法接受数字本身的字符串,并且仅接受数字本身。在您的情况下,字符“\n”(换行符)仍在您的输入中,这就是为什么 nextline() 在您第二次使用它时无法正常工作。

要解决此问题,您可以在调用 scan.nextInt() 之后使用 System.in.read() 从标准输入读取 1 个字符。通过这种方式,您可以从输入中清除换行符,并让 scan.nextLine() 正确读取下一行。

关于java - 使用了扫描仪方法,但键盘输入未显示在命令窗口中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56726327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com