简体   繁体   English

扫描仪没有存储字符串超过“空间”

[英]scanner is not storing strings past a “space”

Firstly, I'm very beginner, but I like to think I mildly understand things. 首先,我是初学者,但我觉得我有点理解。

I'm trying to write a method that will store the user's input into a string. 我正在尝试编写一个将用户输入存储到字符串中的方法。 It works just fine, except if the user puts in a space. 它工作得很好,除非用户放入空间。 Then the string stops storing. 然后字符串停止存储。

public static String READSTRING()   {
        Scanner phrase = new Scanner(System.in);
        String text = phrase.next();
        return text;
    }

I think the problem is that phrase.next() stops scanning once it detects a space, but I would like to store that space in the string and continue storing the phrase. 我认为问题是,一旦检测到空格,phrase.next()就会停止扫描,但我想将该空间存储在字符串中并继续存储该短语。 Does this require some sort of loop to keep storing it? 这是否需要某种循环来保存它?

Use .nextLine() instead of .next() . 使用.nextLine()代替.next()

.nextLine() will take your input until a newline character has been found (when you press enter, a newline character is added). .nextLine()将获取您的输入,直到找到换行符(当您按Enter键时,添加换行符)。 This essentially allows you to get one line of input. 这基本上允许您获得一行输入。

From the Javadoc , this is what we have: 来自Javadoc ,这就是我们所拥有的:

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

Either you can use phrase.nextLine() as suggested by others, or you can use Scanner#useDelimiter("\\\\n") . 您可以按照其他人的建议使用phrase.nextLine() ,也可以使用Scanner#useDelimiter("\\\\n")

Try phrase.nextLine(); 试试phrase.nextLine(); . If I recall correctly, Scanner automatically uses spaces as delimiters. 如果我没记错的话,Scanner会自动使用空格作为分隔符。

Try 尝试

pharse.NextLine();

and you got do an array for limited words 你有一个有限的单词数组

String Stringname = {"word","word2"};

Random f = new Random(6);
 Stringname = f.nextInt();

and you can convert an integer to string 你可以将一个整数转换为字符串

int intvalue = 6697;
 String Stringname = integer.ToString(intvalue);

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

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