1

I am trying to learn Java and want it so you input your name, and if name input matches your name it will print Hello [your name], I am doing this using an if statement and make if so if the input is equal to a string equal to my name it will print hello plus the input. However it doesn't... the else statement is what confuses me because I got it to print the two value to see if they where equal and they both where... help would be appreciated thanks.

package AgeTester;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class HelpSystem {
 public static void main(String args[]) {
  String inp = "Jono";
  JFrame frame = new JFrame("Input Dialogue");

  String name = JOptionPane.showInputDialog(frame, "What is your name?");

  if (inp == name) {
   System.out.printf("Hello", name);
  } else {
   System.out.println(inp + name);
  }
  System.exit(0);
 }
}
eldo
  • 1,327
  • 2
  • 16
  • 27
  • Use `inp.equals(name)` in `if` condition, and `inp.equalsIgnoreCase(name)` to ignore case of letters. – VatsalSura Jul 22 '16 at 10:12
  • There is another error: inside if block, the `System.out.println` takes only one argument. Use `+` (or `StringBuilder`) for string concatenation. – Nick Louloudakis Jul 22 '16 at 10:22

2 Answers2

2

When you compare two strings you should use the .equals(String) method

 if (inp.equals(name)) {

remember: == tests for reference equality (whether they are the same object).

Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
Zeromus
  • 4,472
  • 8
  • 32
  • 40
1

You're not using the equals() method, it's what we use to comapre strings in Java not ==.

if (inp.equals(name)) {
   System.out.printf("Hello", name);
  } else {
   System.out.println(inp + name);
  }
Gherbi Hicham
  • 2,416
  • 4
  • 26
  • 41