gpt4 book ai didi

java - 如何使用扫描仪获取整行输入

转载 作者:行者123 更新时间:2023-12-01 18:11:25 27 4
gpt4 key购买 nike

我知道很多人都问过这个问题,但每个人的答案都是使用 scanner.nextLine()但这对我不起作用。我有这个代码:

if (option == 1) {
System.out.println("What is the name of the goal the task is under?: ");
String goalName = scanner.next();
}

当我使用.next()时我只能得到一个单词,但是当我使用 .nextLine() 时命令行不允许用户输入任何内容,因此它会询问“任务所在的目标名称是什么?:”,然后继续执行程序而不让输入发生。

最佳答案

以下测试代码有效:

package asdfsadf;

import java.util.Scanner;


public class Asdfsadf {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is the name of the goal the task is under?: ");
String goalName = scanner.nextLine();
System.out.println("You entered: ");
System.out.print(goalName);
}

}

因此,唯一的问题是,如果您在此之前使用过扫描仪,则表示您有 scanner.nextInt() ,这会在扫描仪中留下一个空的“行尾”。因此 nextLine 将从上一次调用中获取该行的末尾。要解决此问题,只需创建一个新的扫描仪对象即可。

关于java - 如何使用扫描仪获取整行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32722093/

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