Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two strings in java using command line arguments [duplicate]

Tags:

java

Im a java noob. Basically I am trying to create a program that compares two command line arguments while ignoring case and prints out the lesser of the two strings. Here is what I have so far:

public class CompareStrings
{
   public static void main(String[] args) 
   {
      String s1 = new String(args[0]);
      String s2 = new String(args[1]);

      if ( s1.compareToIgnoreCase(s2) > 0 )
         System.out.println(s2);
      else if ( s1.compareToIgnoreCase(s2) < 0 )
         System.out.println(s1);
      else   
         System.out.println("Both strings are equal.");
   }
}

I keep getting the error

Error: Could not find or load main class CompareString

when I try to run it. What am I doing wrong?

like image 464
user2681595 Avatar asked Aug 14 '13 08:08

user2681595


People also ask

Can we compare 2 strings using == in Java?

We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

Can I use == to compare two strings?

The == operator, known as the equality operator, is used to compare two strings in Java.

How do you compare two strings to see if they are the same?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.

How do you compare 2 strings in Java to find out which one is greater?

Java String compareTo() Method The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).


1 Answers

"Error: Could not find or load main class CompareString"

Your error message says you couldn't load class "CompareString", but your code says your class name is CompareStrings.

like image 111
Jud Avatar answered Oct 01 '22 13:10

Jud