0

I am new to programming and need help with a bit of code I wrote.

This is what I have so far:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner Scan = new Scanner(System.in);
        System.out.println("The program is starting, please be patient...");
        System.out.println("Do you want to start the program? (y/n):");
        String input = Scan.nextLine();
        if (input == "y") {
            System.out.println("Hello World!");
        }
        else {
            System.out.println("Error");
            System.out.println(input + " not recognized!");
        }
    }
}

When I run this, there are no errors, but when I type "y" it runs the else section instead of saying "Hello World!". How can I make it so when I type in "y" it says "Hello World!"?

0

2 Answers 2

2

Correct way to compare is

if(input.equals("y"))
1

Use String#equals instead of ==

if (input.equals("y")) {
            System.out.println("Hello World!");
        }

== compares reference where as String#equals() compares values in String Object

1
  • Thanks for the fast response.
    – JohnDoe
    Mar 17, 2015 at 19:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.