Question

I have a question regarding making String arrays in Java. I want to create a String array that will store a specific word in each compartment of the string array. For example, if my program scanned What is your deal? I want the word What and your to be in the array so I can display it later.

How can I code this? Also, how do I display it with System.out.println();?

Okey so, here is my code so far:

import java.util.Scanner;
import java.util.StringTokenizer;

public class OddSentence {

    public static void main(String[] args) {

        String sentence, word, oddWord;
        StringTokenizer st;

        Scanner scan = new Scanner (System.in);


        System.out.println("Enter sentence: ");
        sentence = scan.nextLine();

        sentence = sentence.substring(0, sentence.length()-1);
        st = new StringTokenizer(sentence);

        word = st.nextToken();


        while(st.hasMoreTokens()) {
            word = st.nextToken();
            if(word.length() % 2 != 0) 

        }

        System.out.println();
    }
}

I wanted my program to count each word in a sentence. If the word has odd numbers of letter, it will be displayed.

Was it helpful?

Solution 3

I agree with what the others have said, you should use String.split(), which separates all elements on the provided character and stores each element in the array.

String str = "This is a string";
String[] strArray = str.split(" ");   //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
  if((strArray[i].length() % 2) == 0) {  //if there is an even number of characters in the string
    System.out.println(strArray[i]);     //print the string
  }
}

Output:

This is string

If you want to print the string when it has an odd number of characters, simply change if((strArray[i].length() % 2) == 0) to if((strArray[i].length() % 2) != 0)

This will give you just a as the output (the only word in the string with an odd number of characters).

OTHER TIPS

Based on what you've given alone, I would say use #split()

String example = "What is your deal?"
String[] spl = example.split(" ");
/*
  args[0] = What
  args[1] = is
  args[2] = your
  args[3] = deal?
*/

To display the array as a whole, use Arrays.toString(Array);

System.out.println(Arrays.toString(spl));

To read and split use String.split()

final String input = "What is your deal?";
final String[] words = input.split(" ");

To print them to e.g. command line, use a loop:

for (String s : words) {
    System.out.println(s);
}

or when working with Java 8 use a Stream:

Stream.of(words).forEach(System.out::println);

Let input be your input string. Then:

String[] words = input.split(" ");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top