Java:只获取用户输入字符串的第一个单词
我一直有点麻烦的家庭作业问题 我需要有一个用户输入字符串作为产品类别。如果用户输入多个单词,我只需要输入第一个单词 规定:我不能使用“如果”语句 这是我到目前为止得到的,但如果只键入一个单词,它就会失败Java:只获取用户输入字符串的第一个单词,java,string,Java,String,我一直有点麻烦的家庭作业问题 我需要有一个用户输入字符串作为产品类别。如果用户输入多个单词,我只需要输入第一个单词 规定:我不能使用“如果”语句 这是我到目前为止得到的,但如果只键入一个单词,它就会失败 Scanner scan = new Scanner (System.in); System.out.println ("Enter a noun that classifies the" + " type of your product:"); Str
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);
使用string.split()
使用string.split()
String类中的方法split(stringregex)
将返回一个在regex字符串上拆分的字符串数组
String test = "Foo Bar Foo Bar"
String[] array = test.split(" ");
//array is now {Foo, Bar, Foo, Bar}
从那里你可以知道如何得到第一个单词
下次遇到困难时,这些方法对于找到新方法非常有帮助 String类中的方法split(String regex)
将返回在regex字符串上拆分的字符串数组
String test = "Foo Bar Foo Bar"
String[] array = test.split(" ");
//array is now {Foo, Bar, Foo, Bar}
从那里你可以知道如何得到第一个单词
下次遇到困难时,这些方法对于找到新方法非常有帮助 您可以使用
String[]array=noon.split(\\s+”)
在空格之间分割,然后使用array[0]
返回第一个单词。您可以使用String[]array=noon.split(\\s+”)
在空格之间分割,然后使用array[0]
返回第一个单词。您可以使用scan.next()
仅获取第一个单词 您可以使用scan.next()
仅获取第一个单词 另一种方法是使用Scanner
类的分隔符,而不是操作整个输入字符串:
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);
请注意,我们使用的是Scanner类的next()
而不是nextLine()
。不是操作整个输入字符串,另一种方法是使用Scanner
类的分隔符:
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);
请注意,我们使用的是Scanner类的next()
而不是nextLine()
。String#split
-String[]parts=noon.split(“”)
那么第一个元素就是第一个单词,不管实际上是否有多个单词……String#split
-String[]parts=noon.split(“”)
那么第一个元素就是第一个单词,不管实际上是否有多个单词……如果您还想使用来自用户的其余数据为新行的下一个单词准备扫描仪,只需在scan.nextLine()之后添加scan.next()
。如果您还想使用用户提供的其余数据为新行的下一个单词准备扫描器,只需在scan.nextLine()
之后添加scan.next()
。默认情况下,扫描器的分隔符是空白,不需要使用分隔符(“”)事实上,我把它包括进来是为了强调使用分隔符的想法。我已经在我的代码注释中添加了这一点。默认情况下,扫描器的分隔符是一个空白,不需要使用分隔符(“”)事实上,我把它包括进来是为了强调使用分隔符的想法。我已经在我的代码注释中添加了这一点。您还可以使用split(“,2)[0]
来避免对其余空间进行不必要的拆分。您还可以使用split(“,2)[0]
来避免对其余空间进行不必要的拆分。