I'm new to programming and logical errors; I've looked for a similar problem but nothing quite matches mine. We have an assignment to make a program where the user enters their first and last name--if the names are the same, it returns "your first and last name are the same" and if the names are different, it returns "your first and last name are different".
My problem is that it keeps returning BOTH answers no matter what names are typed in. If you run it and try your own name in it, you'll see what I mean.
Here's my code (we have to use scanner):
import java.util.Scanner;
public class NameAssignment
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String firstName;
System.out.print("Enter your first name: ");
firstName = stdIn.nextLine();
String lastName;
System.out.print("Enter your last name: ");
lastName = stdIn.nextLine();
if (firstName == lastName);
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are the same.");
if (firstName != lastName);
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
} // end main
} // end class NameAssignment
UPDATE
I tried correcting it with the suggestions below, and here's what it looks like now:
import java.util.Scanner;
public class NameAssignment
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String firstName;
System.out.print("Enter your first name: ");
firstName = stdIn.nextLine();
String lastName;
System.out.print("Enter your last name: ");
lastName = stdIn.nextLine();
if (firstName.equals(lastName))
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are the same.");
else (!firstName.equals(lastName)
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
} // end main
} // end class NameAssignment
I ran it in terminal, and it gave me this:
NameAssignment.java:16: error: ')' expected
else (!firstName.equals(lastName)
^
NameAssignment.java:16: error: not a statement
else (!firstName.equals(lastName)
^
NameAssignment.java:17: error: illegal start of expression
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
^
NameAssignment.java:17: error: ';' expected
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
^
4 errors