如何让Java注册带空格的字符串输入?

问题描述 投票:6回答:4

这是我的代码:

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  String question;
  question = in.next();

  if (question.equalsIgnoreCase("howdoyoulikeschool?") )
    /* it seems strings do not allow for spaces */
    System.out.println("CLOSED!!");
  else
    System.out.println("Que?");

当我试着写“你喜欢学校怎么样?”答案总是“阙?”但它的工作正常,因为“howdoyoulikeschool?”

我应该将输入定义为除String之外的其他内容吗?

java string space
4个回答
9
投票

in.next()将返回以空格分隔的字符串。如果你想阅读整行,请使用in.nextLine()。读完字符串后,使用question = question.replaceAll("\\s","")删除空格。


1
投票

代替

Scanner in = new Scanner(System.in);
String question;
question = in.next();

输入

Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();

这应该可以将空格作为输入。


1
投票

这是在java中获取输入的示例实现,我在salary字段中添加了一些容错,以显示它是如何完成的。如果你注意到,你还必须关闭输入流..享受:-)

/* AUTHOR: MIKEQ
 * DATE: 04/29/2016
 * DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-) 
 * Added example of error check on salary input.
 * TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2) 
 */

import java.util.Scanner;

public class userInputVersion1 {

    public static void main(String[] args) {

    System.out.println("** Taking in User input **");

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your name : ");
    String s = input.nextLine(); // getting a String value (full line)
    //String s = input.next(); // getting a String value (issues with spaces in line)

    System.out.println("Please enter your age : ");
    int i = input.nextInt(); // getting an integer

    // version with Fault Tolerance:
    System.out.println("Please enter your salary : ");
    while (!input.hasNextDouble())
    {
        System.out.println("Invalid input\n Type the double-type number:");
        input.next();
    }
    double d = input.nextDouble();    // need to check the data type?

    System.out.printf("\nName %s" +
            "\nAge: %d" +
            "\nSalary: %f\n", s, i, d);

    // close the scanner
    System.out.println("Closing Scanner...");
    input.close();
    System.out.println("Scanner Closed.");      
}
}

0
投票

由于很长一段时间并且人们一直建议使用Scanner#nextLine(),因此Scanner可以在输入中包含空格。

Class Scanner

扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格。

您可以使用Scanner#useDelimiter()Scanner的分隔符更改为另一种模式,例如line feed或其他。

Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;

System.out.println("Please input question:");
question = in.next();

// TODO do something with your input such as removing spaces...

if (question.equalsIgnoreCase("howdoyoulikeschool?") )
    /* it seems strings do not allow for spaces */
    System.out.println("CLOSED!!");
else
    System.out.println("Que?");
© www.soinside.com 2019 - 2024. All rights reserved.