-1

So I'm fairly new to java and I've been stuck on this question.

Prompt the user for two characters and store them in two char variables. Compare the variables and print “ is less than ” if the first char is less than the second char. Otherwise, print “ is greater than ” if the first char is greater than the first char. Otherwise, print “ is equal to ” if they are equal.

If user enters ‘A’ then ‘B’ print: A is less than B If user enters ‘B’ then ‘A’ print: B is greater than A If user enters ‘A’ then ‘A’ print: A is equal to A

Note: The output above would be printed if the user entered the characters A and B. If the user enters other letters, those letters would be printed. This is the power of variables!

 Scanner letter = new Scanner(System.in);
 String input;
 char firstChar;
 char secondChar;

 System.out.println("Enter two characters:");

 input = letter.nextLine();
 firstChar = input.charAt(0);
 input = letter.nextLine();
 secondChar = input.charAt(0);



  if (firstChar.compareTo(secondChar) < 0)
 {
 System.out.println(firstChar+ " is less than " +secondChar+ "");
 }

  if (firstChar.compareTo(secondChar) > 0)
 {
 System.out.println(firstChar+ " is greater than " +secondChar+ "");
 }

  if (firstChar.compareTo(secondChar) == 0)
 {
 System.out.println(firstChar+ " is equal to " +secondChar+ "");
 }

I'm not sure if I need the String or not or if I can just use
firstChar = letter.next().charAt(0);

David
  • 5,882
  • 3
  • 33
  • 44
asdf1234
  • 1
  • 1

1 Answers1

0

Your problem is in the way that you are using the firstChar variable etcetera.

  char firstChar; // OK

  firstChar = input.charAt(0); // OK

  if (firstChar.compareTo(secondChar) < 0)   // FAIL!

The char type is a primitive type. You can't call methods on a char.

You need to operate on character values directly ... using numeric, relational or bitwise operators; e.g.

  if (firstChar < secondChar)) 

What you were trying to do would have worked if the type of firstChar was Character not char. But in this case, using char is simpler, faster, less code, etcetera.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216