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

Java 如何使用扫描仪获取整行输入,java,Java,我知道很多人都问过这个问题,但每个人的答案都是使用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()时,命令行不允许用

我知道很多人都问过这个问题,但每个人的答案都是使用
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,比如说您有
scanner.nextInt()
,那么会在扫描仪中留下一个空的“行尾”。因此,下一条线路将从上一次通话中截取线路的末尾。要解决此问题,只需创建一个新的scanner对象。

以下测试代码有效:

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,比如说您有
scanner.nextInt()
,那么会在扫描仪中留下一个空的“行尾”。因此,下一条线路将从上一次通话中截取线路的末尾。若要解决此问题,只需创建一个新的扫描仪对象。

@coder,由于您的程序足够小,请将其转换为一个新的扫描仪?这样我们可以自己运行它,以便更好地帮助您。在进入条件之前,您是否使用了扫描仪实例?@coder,由于您的程序足够小,请将其转换为一个新的?这样,我们可以自己运行它,以便更好地帮助您。您在进入条件之前是否使用了扫描仪实例?如果不允许我关闭扫描仪并创建新扫描仪,我需要读取输入,该怎么办?如果不允许我关闭扫描仪并创建新扫描仪,我需要读取输入,该怎么办?