-1

Here's my code in C#:

        string month;
        do
        {
            Console.WriteLine("put month");

            month = Console.ReadLine();
            switch (month)
            {
                case "1":
                    Console.WriteLine("dsad");
                    Console.ReadLine();
                    Console.WriteLine("\neheheh!");
                    Console.WriteLine("\nhihihihi");
                    break;

            }
        }while(month!="Quit");

Here it is in Java:

    Console C = System.console();

    String month;
    int year;

    do {
        month = C.readLine("\nPlease put a valid month: \n");
        switch (month) {
            case "1":

                C.readLine("\nPlease put a valid year: \n");
                System.out.println("\nThe month is January!");
                System.out.println("\nJanuary has 31 days!");
                break; 
        }
    } while (month != "Quit");

My problem is that my code in Java won't terminate even if I type the word "Quit".

This is a follow up to this question.

Community
  • 1
  • 1
ihatecodes
  • 61
  • 4
  • See this: http://stackoverflow.com/questions/1530864/java-why-doesnt-my-string-comparison-work?rq=1 – Joachim Sauer Oct 15 '12 at 07:35
  • 3
    Because that's not how you compare `String`s. `!=` is checking the *reference value*. You may want to start with the Oracle Java tutorials. – Brian Roach Oct 15 '12 at 07:35
  • Also: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – sloth Oct 15 '12 at 07:38

3 Answers3

4

Use equals method for equaling.

do{
}while (!month.equals("Quit"));
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • 1
    thanks to all you guys. im a total newb in java that's why i tend to make it first on c# to test if the codes work xD – ihatecodes Oct 15 '12 at 07:43
3

In Java, use .equals() instead of == for comparing strings:

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

If you use == (or !=), you just test for reference equality, not value equality.

sloth
  • 99,095
  • 21
  • 171
  • 219
0

You should use .equals() instead of == or != for String in Java. Another point, do not use !month.equals("Quit"), it may causes the NullPointerException.

As experienced developers, they always write: !"Quit".equals(month)