简体   繁体   English

Java将字符串中的单词打印到数组中

[英]Java print out words from a string into an array

I want to take user input for whatever words they may enter through a buffered reader and put them into an array. 我想让用户输入他们可能通过缓冲读取器输入的任何单词,并将它们放入数组中。 Then I want to print out each word on a separate line. 然后,我想在单独的一行上打印出每个单词。 So I know I need some sort of a word counter to count the number of words the user inputs. 所以我知道我需要某种类型的单词计数器来计算用户输入的单词数。 This is what I have thus far. 到目前为止,这就是我所拥有的。

import java.text.*;
import java.io.*;

public class test {
    public static void main (String [] args) throws IOException {

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String inputValue;

        inputValue = input.readLine();
        String[] words = inputValue.split("\\s+");

Lets say the users enter the words here is a test run . 可以说,用户在here is a test run输入文字here is a test run The program should count 5 values and print out the words as such 该程序应计算5个值并按原样打印单词

here
is
a
test
run

Any help or suggestions on which way to approach this? 对采用哪种方法有什么帮助或建议?

There really is no need to count the words (unless you really want to). 确实没有必要对字数进行计数(除非您真的想要)。 You could instead use a for-each loop like 您可以改为使用for-each循环,例如

String[] words = inputValue.split("\\s+");
for (String word : words) {
    System.out.println(word);
}

As I said, if you really want to, then you could get the length of an array (your "count") and then use a regular for loop like 就像我说的,如果您真的想要,那么您可以获取数组的length (您的“计数”),然后使用常规的for循环,例如

String[] words = inputValue.split("\\s+");
for (int i = 0; i < words.length; i++) {
    System.out.println(words[i]);
}

If you don't need each word on a separate line, then you could also use Arrays.toString(Object[]) and something like 如果不需要每个单词都在单独的行上,则还可以使用Arrays.toString(Object[])和类似的东西

String[] words = inputValue.split("\\s+");
System.out.println(Arrays.toString(words));

I hope I'm not answering homework. 我希望我不回答作业。 If so you should tag it as such. 如果是这样,则应将其标记为此类。 Here are two approaches you might try. 您可以尝试以下两种方法。

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    String inputValue = input.readLine();
    String[] words = inputValue.split("\\s+");

    // solution 2
    for(int i=0; i<words.length; i++){
        System.out.println(words[i]);
    }

    // solution 1
    System.out.println(inputValue.replaceAll("\\s+", "\n"));

Live Demo: http://ideone.com/bCucIh 现场演示: http//ideone.com/bCucIh

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

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