-1

I looked it over and can't find out the error. It just can't run the last part of finding the first ward. I think my method of getWard is correct and I can't find where is wrong. Please help!

 public static void main(String[] args) {
    Scanner inScanner = new Scanner(System.in);
    String input = getInputString(inScanner);
    int count = getWordCount(input);
    System.out.println("Your string has " + count + " words in it.");
    String first = getWord(input , 1);
    System.out.print("The first word is: " + first);


}
    // TODO Auto-generated method stub

private static String getInputString(Scanner inScanner) {
        System.out.println("Enter a string: ");
        String inputString = inScanner.nextLine();
        return inputString;
}
private static int getWordCount(String input) {

    int count = 1;

    for (int i = 0; i < input.length(); i++) {
        if (input.charAt(i) == ' ') {
            count ++;
        }
    }

    return count;
}
private static String getWord(String input, int n){
    String myString = getWord(input , 1);
    return myString;
}
}
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223

3 Answers3

1

This is going to be endlessly recursive

private static String getWord(String input, int n){
    String myString = getWord(input , 1);
    return myString;
}

looking at your code

I guess you want something like

  return input.split(" ")[0];

But you should also do some null string testing

Also, there does not seem to be any point in passing an int to this method.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0
private static String getWord(String input, int n){
  String myString = getWord(input , 1);
  return myString;
}

will run forever

Use string's split method, e.g. String firstWord = input.split(" ")[0];

You can also see this: How to split a string in Java

Olaf Goj
  • 1
  • 2
  • Use string's split method, e.g. `String firstWord = input.split(" ")[0];` You can also see this: https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java – Olaf Goj Feb 17 '16 at 00:36
0

In your method getWord, it looks like you are having it call itself recursively forever, without stopping anywhere. And you have variable 'n' that is not used at all. Why is that?

Instead of getWord you probably need to use Scanner's method next(), if I am correct, it will return the whole word.

Also, I am pretty sure that is you count all the words, you reach the end of the document, which means that if you want to get the first word, you need to get scanner return to the beginning and start over. But in your place I would check that information too.

Liza
  • 103
  • 1
  • 10