tags:

views:

215

answers:

5

Hi All,

I am stuck on this code.

The code should use the class StringBuilder to build an output string by appending non-vowel characters from its argument in to the result it returns. It needs to identify vowels to be removed using the helper method i created which is public boolean isVowel(char c).

public String shorthand(String in) this is the method I need help with. I have created the stringbuilder but the if condition does not accept isVowel method.

import java.io.*;
import java.util.*;


public class Shorthand
{    

    public boolean isVowel(char c)
   {

       if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A'|| c == 'E'||c == 'I'|| c == 'O'|| c == 'U')
       {
           return true;
       }
       else
       {
           return false;
       }
   }

    //TODO Complete the shorthand method
    public String shorthand(String in) //this is the code I need help with
    {
      StringBuilder vowel = new StringBuilder();

      if (isVowel() == false)
      { 
        vowel.append(in); 
       } 
          return vowel.toString(); 
    }

    //TODO Complete the run method
    public void run() throws IOException
    {
       String yourLine; 
       Scanner sc = new Scanner(System.in); 
       yourLine = sc.nextLine(); 
       while(!yourLine.equals("*"));
       {
            System.out.println("Enter your line of text");
       }
       yourLine = sc.nextLine(); 
    }
}
+1  A: 

You need to pass a char value to the isVowel() method. Try the following:

public String shorthand(String in) 
{
  StringBuilder vowel = new StringBuilder();

  for (int i=0; i < in.length(); i++)
  {
      if (isVowel(in.charAt(i)) == false)
      { 
        vowel.append(in.charAt(i)); 
      }
  } 
  return vowel.toString(); 
}
Chris Knight
+2  A: 

You didn't pass the char c argument of isVowel()

Try this:

public String shorthand(String in) { 
        StringBuilder vowel = new StringBuilder();

        for (char c : in.toCharArray()) {
            if (!isVowel(c)) {
                vowel.append(c);
            }
        }

        return vowel.toString();
}

EDIT: Your run() method seems to be a bit weird...

Maybe the following is what you wanted?

public void run() throws IOException
{
    String yourLine;
    Scanner sc = new Scanner(System.in);
    while (!sc.nextLine().equals("*")) {
        System.out.println("Enter your line of text");
    }
}

On a side note, it doesn't even call the shorthand() method.

ryanprayogo
I have tried this code using Netbeans it when entering text nothing happens it says building and still has the input text box any ideas
luvthug
@luvthug: see my edit above.
ryanprayogo
there's a small typo here - you're appending "in" to the stringBuilder, it of course should be "c".
mdma
@mdma: you are absolutely correct. Fixed above, thanks
ryanprayogo
+1  A: 

You want something like this

public String shorthand(String in)
{
      int length = in.length();
      StringBuilder noVowels = new StringBuilder(length);
      for (int i=0; i<length; i++)
      {
         c = in.charAt(i);
         if (!isVowel(c))
           noVowels.append(c);
      }
      return noVowels.toString(); 
}

PS: Your isVowel method only checks for lowercase. If you want to recognise vowels in both upper and lower case, call Character.toLowerCase in the first line of isVowel.

EDIT: I didn't comment on the run() method because I presumed that was work in progress. As you're having problems with that, here's a corrected version.

public static void main(Stirng[] args) throws IOException
{
   Scanner sc = new Scanner(System.in);
   for(;;) {
    System.out.println("Enter your line of text");
    String line = sc.nextLine();
    if (line.equals("*")) break;
    String shortHandLine = shorthand(line);
    System.out.println(String.format("Shorthand form of %s is %s", line, shortHandLine));
   }    
}

As this is an application, you can right click and run this in most IDEs.

mdma
+1  A: 

Please tag this as homework

To the point: lots of problems here

First, you need to have your main actually call shortHand on each line, and probably print the results.

Second, your shorthand function should iterate over all the characters of the string, right now you are not doing that. You will be passing each character to the isVowel function.

Uri
also, the 'strong text' typo on the `if (isVowel...)` line
ryanprayogo
+1  A: 

There is a lot to be learned from your code.

On returning a boolean expression

Here's an improved version of isVowel(char ch):

public boolean isVowel(char ch) {
    ch = Character.toLowerCase(ch);
    return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
}

Note two things here:

  • ch is simplified to the lower case form, so you have much fewer checks
  • There is no if statement.

There is an important lesson here: you should never write something like this:

if (expression) {
   return true;
} else {
   return false;
}

You should always instead write:

return expression;

This is much, much clearer.


On familiarizing yourself with the Java library

Note the use of Character.toLowerCase in the above code. In fact, it's possible to make the code even simpler by using, e.g. String.indexOf:

public boolean isVowel(char ch) {
    return "aeiouAEIOU".contains("" + ch);
}

This uses String.contains, using string concatenation to effectively convert the char to a String (which implements CharSequence).

API link

See also


Don't compare against boolean constants

Beginners tend to write something like this:

if (expression1 == false) {
}
//...
if (expression2 == true) {
}

Especially in Java, you should learn to write like this instead:

if (!expression1) {
}
//...
if (expression2) {
}

This is much clearer, and much less error prone.

See also


On iterating over every character of a String

Here's a simple loop to show how the indexed way of doing this:

    String s = "Abracadabra";
    for (int i = 0; i < s.length(); i++) {
        System.out.print("[" + s.charAt(i) + "]");
    } // prints "[A][b][r][a][c][a][d][a][b][r][a]"

This uses the length() and charAt(int index) methods of String.

Alternatively, if you don't need the index, you can also use String.toCharArray() to do a foreach on the char[] instead. This is not space efficient (the char[] has to be newly allocated to guarantee immutability), but is very readable and concise:

    String s = "Abracadabra";
    for (char ch : s.toCharArray()) {
        System.out.print("[" + ch + "]");
    } // prints "[A][b][r][a][c][a][d][a][b][r][a]"

See also


On the software development process

As others have mentioned, your run method is very problematic: it currently results in an infinite loop.

What you could have done instead is write what are called "method stubs" for isVowel (e.g. simply return true;) and shorthand (e.g. simply return "";). They're not correct yet, but the important thing is that they compile for now. This gives you time to focus on run, to make sure that you have a properly working loop, and that you are able to extract the relevant input from the user. You should bring the code to the point where it compiles and runs, so you can test and be confident that your run does what it needs to do. At that point, you can start to fill out to previously stubbed methods, implementing the proper functionalities as required.

If you're having difficulty achieving that, you can ask questions about that particular aspect of the homework (but search for it first on stackoverflow!). This gives you high quality and focused answers on problems as you encounter them (as oppose to posing such a problematic code that people can go all over the place on it), and is therefore more instructive for your own sake.

The question is also likely to be more useful to others since it's more general in context (i.e. it's about how to write a user prompt loop, not about how to do your homework) (in contrast, this question is currently titled public String shorthand(String in)).

Another thing you can do is perform what are called unit tests. isVowel is a GREAT candidate for this: to test its correctness, you'd have to know how to invoke it (something which you apparently are having problem with).

All of this seems to be unnecessary work at first. Presumably the unit tests aren't part of the homework (though it probably should be), and writing stubs and then replacing it with something else seems like a waste of time and that you should just get it right the first time instead. Precisely because this is a homework assignment, though, you should adopt and practice the methodologies of good software development process. It's for your own good.

See also

polygenelubricants