Java Can compareTo Handle All String Comparisons in Java?

  • Thread starter Thread starter tbrown427
  • Start date Start date
  • Tags Tags
    Java
Click For Summary
The Java code provided is intended to compare two strings, "rabbits" and "capes," using the compareTo method. However, the output is consistently "capes rabbits" regardless of the comparison result. This occurs because both the if and else branches contain the same print statement, leading to no variation in output. To achieve the intended functionality, the code should differentiate the outputs based on the comparison result, ensuring that different messages are printed for each condition. The current structure fails to utilize the comparison effectively, resulting in a lack of meaningful output.
tbrown427
Messages
1
Reaction score
0
I can't get this to test all the way through

Code:
import java.util.Scanner;

public class OrderStrings {
   public static void main (String [] args) {
      String firstString;
      String secondString;

      firstString  = "rabbits";
      secondString = "capes";

     if (secondString.compareTo(firstString) >0){
         System.out.println("capes rabbits");
     }
     else {
         System.out.println("capes rabbits");
     }
      return;
   }
}
 
Technology news on Phys.org
This code compiles and executes, but the output is always
capes rabbits

Look at your if else statement and notice it makes no difference the result of compareTo; it always just prints the above.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 12 ·
Replies
12
Views
15K
Replies
8
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 2 ·
Replies
2
Views
13K