为什么我的代码不能用Java工作?

时间:2012-10-15 07:31:42

标签: c# java

这是我在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");

这是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");

我的问题是,即使我输入单词“Quit”,我的Java代码也不会终止。

这是this question的后续行动。

3 个答案:

答案 0 :(得分:4)

使用equals方法进行等效。

do{
}while (!month.equals("Quit"));

答案 1 :(得分:3)

在Java中,使用.equals()代替==来比较字符串:

  

将此字符串与指定对象进行比较。当且仅当参数不为null并且是一个表示与此对象相同的字符序列的String对象时,结果才为真。

如果使用==(或!=),则只测试引用相等,而不是值相等。

答案 2 :(得分:0)

对于Java中的String,您应该使用.equals()而不是==!=。 另一点,不要使用!month.equals("Quit"),它可能会导致NullPointerException。

作为有经验的开发人员,他们总是写:!"Quit".equals(month)

相关问题