I'm trying to take input from the user as part of a text-based adventure game. The input from the user can only be 2 words, a verb and a noun, and I want to split the string input into 2 words using the split() method and store that as a string array.
Here is some of the code:
in = input.nextLine();
inArray = Arrays.toString(in.split(" ", 2));
I get an error saying "Type mismatch: cannot convert from String to String[]"
How do I split a string and store it as a string array?
in.split(" ", 2)
creates an array of String
elements. Arrays don't generally print easily. Using Arrays.toString()
is a good way to get a nice String
representation of the array object. If you want to store the array object, use the result of in.split(" ", 2)
, and format it as a string only when you need to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.