Jack Nguyen
Jack Nguyen

Reputation: 103

Does my method work for finding each word in a string

As the title suggests, I'm trying to make a method that will individually work on each word of a string. I've gotten the code down but I'm not sure if it is right. So I ran a couple of tests to see if it prints out appropriately. After multiple tries and absolutely nothing printing out. I need help. Can anyone find anything wrong my code?

public static String build( String str4, one test){
     Scanner find = new Scanner( System.in);
     String phrase = " ";
     while ( find.hasNext()){
         String word = find.next();
         word = test.change(word);
         phrase += word + " ";

     }
     return phrase;
}

The method change just changes the word to pig latin ( my intended goal ).

Here are the simple lines in my main method:

 String str4 = "I am fluent in pig latin";
    System.out.println (test.build(str4, test));

I intended for this code to print out this:

Iyay amyay uentflay inyay igPay atinLay

Upvotes: 2

Views: 97

Answers (2)

Jason C
Jason C

Reputation: 40406

You have:

Scanner find = new Scanner( System.in);

Which means you're reading from user input.

You also have this str4 parameter, but you're not actually using it. You seem to have inadvertently used System.in as your input string source when you really meant to use your str4 parameter. Hence, nothing happens, as find.next() is waiting for input from the console rather than using the string you passed in.

You probably mean:

Scanner find = new Scanner(str4);

Upvotes: 2

Nick Louloudakis
Nick Louloudakis

Reputation: 6015

You attempt to get some input inside your function, using the Scanner instance, giving user input as its construction argument.

In order to print what is going to be returned, add this line:

System.out.println (phrase);

before your return statement.

What I am guessing though, is you are mistakenly using user input. Try this instead:

public static String build( String str4, one test){
 Scanner find = new Scanner(str4);
 String phrase = " ";
 while ( find.hasNext()){
     String word = find.next();
     word = test.change(word);
     phrase += word + " ";
 }
 //Print your phrase here if you want.
 System.out.println(phrase);
 return phrase;

}

Upvotes: 4

Related Questions