Reputation: 113
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. Does this require some sort of loop to keep storing it?
Upvotes: 1
Views: 191
Reputation: 82
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);
Upvotes: 0
Reputation: 8366
From the Javadoc, this is what we have:
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")
.
Upvotes: 1
Reputation: 36
Try phrase.nextLine();
. If I recall correctly, Scanner automatically uses spaces as delimiters.
Upvotes: 0
Reputation: 44449
Use .nextLine()
instead of .next()
.
.nextLine()
will take your input until a newline character has been found (when you press enter, a newline character is added). This essentially allows you to get one line of input.
Upvotes: 3