1

My program kind of gets stuck after the readLine call, the if statements don't work. What am i doing wrong? #java-first-timer

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;


public class nums {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));               
        System.out.println("Number Mania!!!");
        System.out.println("Pick your favourite number from 1 to 5");
        String favNum = br.readLine();
        if (favNum=="3"){
            System.out.println("Your favourite number is three!");
        }
        else{
            System.out.println("hi!");
        }
    }
}
JoseSwagKid
  • 389
  • 1
  • 6
  • 12
  • 3
    Another day, another `==` String comparison... This question may interest you: [how do I compare Strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). Then this will be also interesting: http://stackoverflow.com/questions/9698260/what-makes-reference-comparison-work-for-some-strings-in-java – Pshemo Feb 07 '13 at 00:54

2 Answers2

8

Use favNum.equals("3") instead of favNum == "3". You should almost never use == to compare objects; use .equals instead. (There are a few rare exceptions, but you won't need to worry about them until you learn a fair bit more Java.)

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
2

Use favNum.equals("3") to compare Strings... actually, there is very few occasions that you should use == comparator for String comparison.

As the second suggestion, you should consider start using the java.util.Scanner class. Your code could be like this:

import java.util.Scanner;

public class nums {
    public static void main(String[] args) {
        Scanner scann = new Scanner(System.in);               
        System.out.println("Number Mania!!!");
        System.out.println("Pick your favourite number from 1 to 5");
        int favNum = scann.nextInt();
        if (favNum == 3){
            System.out.println("Your favourite number is three!");
        }
        else{
            System.out.println("hi!");
        }
    }
}

Hope I could help.

Giovani Guizzo
  • 527
  • 3
  • 13
  • Do you know what makes it hang when using "=="? I'd prefer if it crashed instead, so at least I knew something was wrong – JoseSwagKid Feb 07 '13 at 01:12
  • 1
    @JoseSwagKid `==` tests for reference equality while `.equals()` tests for value equality. You should look at links given by Pshemo – Smit Feb 07 '13 at 01:14