gpt4 book ai didi

java - 在java中从键盘获取多行然后单个字符

转载 作者:行者123 更新时间:2023-12-02 01:50:30 28 4
gpt4 key购买 nike

我输入:

  • 乔·史密斯(按 Enter 键)
  • IT 工程师(按 Enter 键)
  • Y(按 Enter 键)

然后发生的情况是,循环再次出现,但无法输入 your first and last name第二次。

String name = s.nextLine();循环执行一次后似乎总是空行。

这是为什么?

代码:

Scanner s = new Scanner(System.in);

do {
System.out.printl('Enter your first and last name:');
String name = s.nextLine();

System.out.printl('Enter your job description:');
String job = s.nextLine();

System.out.println("Press Y for loop ..");
char answer = s.next().charAt(0);
} while(answer == 'Y');

最佳答案

System.out.printl() 应该是 System.out.println()

您应该对字符串使用双引号。

 System.out.printl('Enter your first and last name:');//<----single quote

变量 answer 超出范围,因为在 java 中,范围仅限于 {}。在 do-while 循环之前声明 answer(位于顶部)。

不要使用char answer = s.next().charAt(0);,而是使用answer = s.nextLine().charAt(0);

更多信息请查看Scanner is skipping nextLine() after using next() or nextFoo()?

这是您修改后的代码:

    public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char answer; //<----declare the variable here

do {
System.out.println("Enter your first and last name:"); //<---use double quotes
String name = s.nextLine();

System.out.println("Enter your job description:");//<---use double quotes
String job = s.nextLine();

System.out.println("Press Y for loop ..");
answer = s.nextLine().charAt(0); //<---use nextLine() here
}while(answer == 'Y');
}

关于java - 在java中从键盘获取多行然后单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53052290/

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