当我学习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);
}
}
但是有一个问题。如果你运行它并输入一个带空格的短语,它只会将字符串保存到空格中。如何保存整个字符串?
答案 0 :(得分:5)
使用nextLine()而不是next()
答案 1 :(得分: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);
}
}
答案 2 :(得分:0)
改为使用缓冲读卡器。
BufferedReader reader =
new BufferedReader
(new
InputStreamReader
(System.in));
String input = reader.readLine();
System.out.println(input);