String methods: CompareTo and Equals
Maybe I misunderstand what is meant by the
CompareTo and Equals methods of String.
Here's my code, if I want to use an if statement, how would I do so using these methods?
I keep getting syntax errors, and believe that I may not be using these methods correctly.
If using an IF statment is not best way to demonstrate these two methods, please explain why and
what I should do to you use these methods and get the inferred results.
Just so you know, I am just asking user for a sentence [input string] and then using different string methods to print different output, based on what each method returns.
Code:
import java.util.*;
import javax.swing.*;
public class stringEx2 {
public static void main(String [] args)
{
String input = JOptionPane.showInputDialog
("Input a sentence or phrase and we'll give some details about it");
System.out.println("Your sentence : " +input);
//length():gives length of string input
System.out.println("The number of characters in your sentence is " +input.length());
//charAt: gives position of character in string
System.out.println("The 5th character in your sentence is " +input.charAt(4));
//compareTo: gives comparison of strings
if (input.compareTo("Hello") > 0)
System.out.println("You typed the lucky word " +input "/. So Hello to you!!");
else
System.out.println("You did not type the lucky word : Hello");
//equals : decides if string has same characters as string passed
if (input.equals("Hello World"))
System.out.println("You typed the lucky phrase " +input "/. So Hello to you!!");
else
System.out.println("You did not type the lucky phrase : Hello World");
System.exit(0);
}
}