如何让Java用空格注册字符串输入?
这是我的密码:如何让Java用空格注册字符串输入?,java,string,space,Java,String,Space,这是我的密码: 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
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?");
当我试着写“你喜欢学校吗?”时,答案总是“你喜欢学校吗?”但写“你喜欢学校吗?”
我是否应该将输入定义为字符串以外的内容?in.next()
将返回以空格分隔的字符串。如果要阅读整行,请使用.nextLine()中的
。读取字符串后,使用question=question.replaceAll(“\\s”,“”)
删除空格。而不是
Scanner in = new Scanner(System.in);
String question;
question = in.next();
输入
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
这应该能够将空格作为输入。这是一个在java中获取输入的示例实现,我在salary字段上添加了一些容错功能,以展示它是如何完成的。如果注意到,还必须关闭输入流。。享受:-)
由于时间很长,而且人们一直建议使用
Scanner#nextLine()
,因此Scanner
还有一种可能会占用输入中包含的空间
扫描器使用定界符模式将其输入拆分为标记,默认情况下,定界符模式匹配空白
您可以使用Scanner#use delimiter()
将Scanner
的分隔符更改为另一种模式,例如换行符
或其他模式
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?");
我今天在Java中发现了一个非常奇怪的东西- 如果您从用户输入的内容不止一件,请说
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);
所以,如果我们运行这个程序,它可能会询问这3个输入,然后说我们的输入值是10,2.5,“欢迎使用java”
程序应该按原样打印这3个值,因为我们使用了nextLine(),所以它不应该忽略我们在变量s中输入的空格后的文本
但是,您将得到的输出是-
10
2.5
就这样,它甚至不会提示输入字符串。
现在我正在读关于它的书,说实话,我的理解还有一些差距,我所能理解的是在接受int输入后,然后是双输入,当我们按enter键时,它认为这是提示,忽略了nextLine()
所以把我的代码改成这样-
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);
这项工作做得很完美,因此它与上一个示例中存储在键盘缓冲区中的“\n”之类的内容有关,我们可以忽略使用此选项
如果有人知道,请帮我解释一下。谢谢!in.nextLine()正是我想要的。出于好奇,我为什么要删除空格?@user1687772这现在有点旧了,但我想Osiris补充说,因为在你的代码中,你是在与
howdoyoulikeschool?
进行比较,所以没有空格。在同一个扫描器中。input.nexLine()不起作用。如果我将输入值设为10,4.0,请测试代码。在获得输入值和双精度值后,我可以通过使用input.next()获得我给出的句子的第一个单词,但是当我尝试使用input.nextLine()时。它不起作用。还有一件事,如果当时先输入输入语句,我可以使用input.nextLine()获得完整的句子。是否有人遇到过类似的情况???如果您仍然好奇,可能会重复:
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);