What i'm trying to do below in the code, is get the user to enter two sepearate strings i know i have used first name and last name but just ignore that. So the user enters two strings and it should print the longest string. my program does not always do this. what do i need to change to make it work?
import java.util.Scanner;
public class Q2
{
public static void main(String args [])
{
Scanner keyboardIn = new Scanner(System.in);
String Fname;
String Lname;
System.out.print("Please enter first name: ");
Fname=keyboardIn.nextLine();
System.out.print("Please enter last name: ");
Lname=keyboardIn.nextLine();
if(Fname.compareTo(Lname) < 0)
{
System.out.println(Lname + " Is longest ");
}
else if(Fname.compareTo(Lname) > 0)
{
System.out.println(Fname + " Is longest ");
}
}
}
You should use the length
import java.util.Scanner;
public class Q2 {
public static void main(String args[]) {
Scanner keyboardIn = new Scanner(System.in);
String Fname;
String Lname;
System.out.print("Please enter first name: ");
Fname = keyboardIn.nextLine();
System.out.print("Please enter last name: ");
Lname = keyboardIn.nextLine();
if (Lname.length() > Fname.length()) {
System.out.println(Lname + " Is longest ");
} else if (Fname.length() > Lname.length()) {
System.out.println(Fname + " Is longest ");
} else {
// Both are of same length
}
}
}