Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Help with a method

  1. May 23, 2007 #1
    I'm very new to Java and I was looking for some help on this particular problem.

    I need to create a method that takes a String as a parameter and returns "true" if the parameter is the letter Y or the letter N (in either upper or lower case), or false otherwise.

    Most of the methods we've been working on are numbers (integers mostly) not strings, so this one confuses me quite a bit. How do you make the computer look for a certain character like y, Y, n, N. I don't want to declare them as variables, I just want Java to see them as letters.

    I have:
    public static boolean isYorN(String str)
    {
    boolean character;
    switch (character)
    {
    case 'y':
    character = true;
    return true;
    break;

    case 'Y':
    character = true;
    return true;
    break;

    case 'n':
    character = true;
    return true;
    break;

    case 'N':
    character = true;
    return true;
    break;

    default:
    character = false;
    return false;

    }
    }
    }

    I think a switch case is the best method, but I'm missing something about naming because all my compiling errors are telling me that I have incompatible types (i.e. found: boolean, required: int).

    Thank you in advance for any help.
     
  2. jcsd
  3. May 25, 2007 #2
    The switch would be the best method if you were looking at a single character.
    I would try looping through an array testing each character.
     
  4. May 26, 2007 #3
    Well, I would stay away from switch statements if possible.

    I would first check if the String(bottom line it is sequence(array) of chars) is of length 1 if not return false.

    if(str == null || str.length != 1){
    return false;
    }

    now since the string is of length 1, lets get the char and see if it is N or Y.

    char chr = Charachter.toUpperCase(str.getCharAt(0));

    return char == 'N' || char == 'Y';
     
  5. May 28, 2007 #4

    t!m

    User Avatar

    I'm sure you meant return chr == 'N' || chr == 'Y';

    I think haki's way is the smartest here, but as the most basic you could also just do:

    return str.equals("Y") || str.equals("y") || str.equals("N") || str.equals("n");
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Help with a method
Loading...