简体   繁体   中英

Java: taking only the first word of a user input string

Homework question that I've been having a little trouble with...

I need to have a user input string as a product category. If the user inputs more than one word, I need to take only the first word typed.

Stipulation: I cannot use 'if' statements.

Here's what I have so far, but it fails if only one word is typed.

Scanner scan = new Scanner (System.in);
System.out.println ("Enter a noun that classifies the"
                    + " type of your product:");

String noun = scan.nextLine();
int n = noun.indexOf(" ");
String inputnoun = noun.substring(0,n);

Use string.split()

Scanner scan = new Scanner (System.in);
System.out.println ("Enter a noun that classifies the"
                    + " type of your product:");

String noun = scan.nextLine();
String inputnoun = noun.split(" ")[0];

您可以使用scan.next()仅获取第一个单词。

The method split(String regex) in the string class will return an array of strings split on the regex string.

String test = "Foo Bar Foo Bar"
String[] array = test.split(" ");
//array is now {Foo, Bar, Foo, Bar}

From there you can figure out how to get the first word.

Next time you are stuck, the Java API pages are very helpful for finding new methods.

您可以使用String[] array = noun.split("\\\\s+")在空格之间进行分割,然后使用array[0]返回第一个单词。

Instead of manipulating the entire input String, another way is to use the delimiter of the Scanner class:

Scanner scan = new Scanner(System.in);

// Following line is not mandatory as the default matches whitespace
scan.useDelimiter(" ");      

System.out.println("Enter a noun that classifies the"
                    + " type of your product:");

String noun = scan.next();
System.out.println(noun);

Note that we are using next() instead of nextLine() of the Scanner class.

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.

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