-1

I am supposed to read in a string, convert it to lowercase, then return the first character in the string. If the first character is not a string I'm supposed to print \0.

I have tried:

String ch = sc.nextLine();
char c = ch.charAt(0);
if (Character.isLetter(c)) {
    ch = ch.toLowerCase();
    c = ch.charAt(0);
    return c;
}
return '\0';
theduck
  • 2,589
  • 13
  • 17
  • 23

2 Answers2

0

You need to change char variables to String variables with String.valueOf(c) before you return them.

String ch = sc.nextLine();
char c = ch.charAt(0);
      if (Character.isLetter(c)) {
            ch = ch.toLowerCase();
            c = ch.charAt(0);
            return String.valueOf(c);
        }
   return String.valueOf('\0');
}

Samuel
  • 52
  • 7
0

That exception means that your scanner didn't find anything to return from its' source. Strings in java are not like C strings where they have at least one character ('\0'). You can protect the program from failing with the following addition:

    try
    {
        String ch = sc.nextLine();
        ch = ch.toLowerCase();
        char c = ch.charAt(0);
        if (Character.isLetter(c))
        {
            return c;
        }
        return '\0';
    }
    catch(StringIndexOutOfBoundsException ex)
    {
        System.out.println("You have entered an empty string");
    }
}
NickDelta
  • 3,697
  • 3
  • 15
  • 25