C Eason
C Eason

Reputation: 39

print even words from string input?

I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words. For example, if the user entered

I had a dream that Jake ate a blue frog, 

The output should be

had dream Jake a frog

I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:

import java.util.Scanner;

public class HW2Q1
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter a sentence");
        String sentence = keyboard.next();

        System.out.println();
        System.out.println(sentence); 
    }
}

Upvotes: 0

Views: 2834

Answers (5)

Paul Back
Paul Back

Reputation: 1319

Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:

import java.util.Scanner;

public class HW2Q1 {
    public static void main(String[] args)
    {
        System.out.println("Enter a sentence");

        // get input and convert it to a list
        Scanner keyboard = new Scanner(System.in);
        String sentence = keyboard.nextLine();
        String[] sentenceList = sentence.split(" ");

        // iterate through the list and write elements with odd indices to a String
        String returnVal = new String();
        for (int i = 1; i < sentenceList.length; i+=2) {
            returnVal += sentenceList[i] + " ";
        }

        // print the string to the console, and remove trailing whitespace.
        System.out.println(returnVal.trim());
    }
}

Upvotes: 0

Mathews Mathai
Mathews Mathai

Reputation: 1707

While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.

String newsent;
int i; 
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
 if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
 {
 i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
  {
 newsent=newsent + sentence.charAt(i);
  i++;
   }
   newsent=newsent+" "; //add space at the end of even word added to the newsent
}

}

 System.out.println(newsent.trim()); 
// removes the extra space at the end and prints newsent

Upvotes: 1

achabahe
achabahe

Reputation: 2565

you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:

regex="[ ]+";

the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more) your code might look like this

Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
    finalresult+=chunks[i*2]+" ";//means  finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);

Upvotes: 1

Kicking Bird
Kicking Bird

Reputation: 3

Since you said you are a beginner, I'm going to try and use simple methods.

You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).

If you get something like Index out of range -1, manipulate the input string by adding a space to the end.

Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.

You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.

Upvotes: 0

Shaun
Shaun

Reputation: 5531

I dont want to give away the answer to the question (for the test, not here), but I suggest you look into String.Split() From there you would need to iterate through the results and combine in another string for output. Hope that helps.

Upvotes: 2

Related Questions