简体   繁体   English

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

[英]How do I make Java register a string input with spaces?

Here is my code:这是我的代码:

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?");

When I try to write "how do you like school?"当我试着写“你喜欢学校吗?” the answer is always "Que?"答案总是“阙?” but it works fine as "howdoyoulikeschool?"但它作为“howdoyoulikeschool?”工作正常。

Should I define the input as something other than String?我应该将输入定义为字符串以外的其他内容吗?

in.next() will return space-delimited strings. in.next()将返回以空格分隔的字符串。 Use in.nextLine() if you want to read the whole line.如果您想阅读整行,请使用in.nextLine() After reading the string, use question = question.replaceAll("\\\\s","") to remove spaces.读取字符串后,使用question = question.replaceAll("\\\\s","")删除空格。

Since it's a long time and people keep suggesting to use Scanner#nextLine() , there's another chance that Scanner can take spaces included in input.由于时间很长并且人们一直建议使用Scanner#nextLine() ,因此Scanner可能会在输入中包含空格。

Class Scanner 类扫描器

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Scanner 使用分隔符模式将其输入分解为标记,默认情况下与空格匹配。

You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.您可以使用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?");

I found a very weird thing in Java today, so it goes like -我今天在 Java 中发现了一个非常奇怪的东西,所以它就像 -

If you are inputting more than 1 thing from the user , say如果您从用户输入超过 1 项内容,请说

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s所以,看起来如果我们运行这个程序,它会要求这 3 个输入并说我们的输入值为 10, 2.5,“欢迎使用 java” 程序应该按原样打印这 3 个值,因为我们已经使用了 nextLine () 所以它不应该忽略我们在变量s 中输入的空格后的文本

But, the output that you will get is -但是,您将获得的输出是 -

10
2.5

And that's it, it doesn't even prompt for the String input.就是这样,它甚至不提示输入字符串。 Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().现在我正在阅读它,老实说,我的理解仍然存在一些差距,我所能弄清楚的只是在我们按回车键输入 int 和双输入之后,它认为这是提示并忽略了下一行()。

So changing my code to something like this -所以把我的代码改成这样 -

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

does the job perfectly, so it is related to something like "\\n" being stored in the keyboard buffer in the previous example which we can bypass using this.完美地完成了这项工作,因此它与前面示例中存储在键盘缓冲区中的“\\n”之类的东西有关,我们可以使用它绕过。

Please if anybody knows help me with an explanation for this.如果有人知道请帮我解释一下。

Instead of代替

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

Type in输入

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

This should be able to take spaces as input.这应该能够将空格作为输入。

This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done.这是在 java 中获取输入的示例实现,我仅在工资字段上添加了一些容错以显示它是如何完成的。 If you notice, you also have to close the input stream .. Enjoy :-)如果您注意到,您还必须关闭输入流.. 享受 :-)

/* 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.");      
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM