I'm trying to create a program where it takes the first character of the Last name and place the person in a group due to the name.
I tried comparing the words to numbers i.e. a=1, s=19, etc.
any help at all would be appreciated

package GroupAssignment;
import System.*;
 * Bushra Osman
public class Program
	public static void main(String[] args)
		int group;
		String fn, ln;
		Console.Write("Enter your first name: ");
		fn = Console.ReadLine();
		Console.Write("Enter your last name: ");
		ln = Console.ReadLine();
		Console.Write(fn+" "+ln);
		Console.Write(" is part of group ");
		if ((ln > 0) && (ln <= 9))
			group = 1;
		else if ((ln >= 10) && (ln <= 19))
			group = 2;
		else if ((ln >= 20) && (ln <= 26))
			group = 3;
10 Years
Discussion Span
Last Post by bmanoman

You cannot compare string with number, the way you are doing it. however you can compare strings with equals() or equalsIgnoreCase() methods of String.

What is it that you try to compare, e.g. 0 to 9 , 10 to 19 and etc...? you are trying to compare a last name say, Smith with 20.?


You want to compare characters, not strings

char c =  ln.toUpperCase().charAt(0) // gets the first letter in the String
if (c >= 'A' && c <= 'K') group = 1;

although you can compare characters to integers, its better to compare characters to other characters because it makes your code more readable

also make sure to use the toUpperCase() or toLowerCase() methods because 'A' doesn't equal 'a'

Votes + Comments
good explanation

you could use:

if( ln.charAt(0).equalsIgnoreCase( 'a' ) )

sorry, but that first line of code doesn't even compile because you tried to call the equalsIgoreCase method on a char. You can't call any methods on chars

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.