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.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

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