【问题标题】:How can I obtain a string with spaces from System.in?如何从 System.in 中获取带空格的字符串?
【发布时间】:2013-06-04 21:23:14
【问题描述】:

我在学习 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);
    }

}

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

【问题讨论】:

    标签: java string input


    【解决方案1】:

    使用 nextLine() 代替 next()

    【讨论】:

      【解决方案2】:

      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);
      }
      

      }

      【讨论】:

        【解决方案3】:

        改用缓冲阅读器。

        BufferedReader reader =
        new BufferedReader
        (new
        InputStreamReader
        (System.in));
        String input = reader.readLine();
        System.out.println(input);
        

        【讨论】:

          猜你喜欢
          • 2022-12-29
          • 1970-01-01
          • 1970-01-01
          • 2021-07-08
          • 1970-01-01
          • 2021-07-23
          • 2019-08-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多