Java Can compareTo Handle All String Comparisons in Java?

  • Thread starter Thread starter tbrown427
  • Start date Start date
  • Tags Tags
    Java
AI Thread 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.
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Replies
12
Views
15K
Replies
2
Views
2K
Replies
2
Views
2K
Replies
2
Views
2K
Replies
3
Views
1K
Replies
3
Views
4K
Replies
2
Views
13K
Back
Top