-1

我在学习 Java 时遇到了这个程序:

package com.nathan2055.booksamples;

import static java.lang.System.out;
import java.util.Scanner;

/**
 * @author Nathan2055
 */
public class Copycat {

    private static Scanner keyboard;

    /**
     * @param args
     */
    public static void main(String[] args) {
        keyboard = new Scanner(System.in);

        out.println("This program will copy whatever you type.");
        out.println("Please enter a phrase:");

        String inputPhrase = keyboard.next();
        out.println();
        out.println(inputPhrase);
    }

}

但是有一个问题。如果您运行它并输入一个带有空格的短语,它只会将字符串保存到空格中。我怎样才能让它保存整个字符串?

4

3 回答 3

5

使用 nextLine() 而不是 next()

于 2013-06-04T21:25:44.843 回答
3

next()方法返回以空格分隔的字符串,如果您想使用整行nextLine而不是next().

public class Tester {

private static Scanner keyboard;

/**
 * @param args
 */
public static void main(String[] args) {
    keyboard = new Scanner(System.in);

    out.println("This program will copy whatever you type.");
    out.println("Please enter a phrase:");

    String inputPhrase = keyboard.nextLine();
    out.println();
    out.println(inputPhrase);
}

}

于 2013-06-04T21:27:32.460 回答
0

请改用缓冲阅读器。

BufferedReader reader =
new BufferedReader
(new
InputStreamReader
(System.in));
String input = reader.readLine();
System.out.println(input);
于 2013-06-04T21:41:10.990 回答