2

我有一个程序,当用户输入心情时,它会输出一个基于它的报价。我需要告诉程序
if the user is happy, then output this text问题是,我不知道如何让程序识别输入并基于它输出文本......这是我到目前为止所拥有的代码。

import java.util.Scanner;
public class modd {
    public static void main(String arrgs[]) {
        System.out.println("Enter your mood:");
        Scanner sc = new Scanner(System.in);
        String mood = sc.nextLine();

        if (sc = happy) {
            System.out.println("test");

            if (sc = sad) {
                System.out.println("I am sad");
            }
        }
    }
} 
4

6 回答 6

3

不能像这样比较字符串

if (sc = happy)  // also, you never declare a happy variable. So use the 
                 // stirng literal like I did below
// also can't compare to Scanner instance
// instead compare to mood

使用等于

if ("happy".equals(mood)) {  // Caught commenter, can't use sc to compare, use mood
    // do something
}

此外,如果将来您需要使用 = 操作进行比较(对于字符串以外的任何内容),您将使用双 ==

于 2013-11-07T02:58:00.920 回答
1

我认为你可以如何解决这个问题是通过指定一组预定义的输入参数供用户选择,然后根据那里的选择做出相应的响应,例如:

 System.out.println ("Enter you mood: [1 = happy,2 = sad,3 = confused]");
 int input = new Scanner(System.in).nextInt ();

 switch (input)
 {
   case 1:  System.out.println ("I am happy");break;
   case 2:  System.out.println ("I am sad");break;
   default: System.out.println ("I don't recognize your mood");
 }
于 2013-11-07T03:19:52.970 回答
1

始终使用 .equals(..) 方法来比较字符串值..

if (mood.equals("happy")) 
  System.out.println("test");

if (mood.equals("sad")) 
    System.out.println("I am sad");
于 2013-11-07T03:01:51.960 回答
1

应该是这样的

    if ("happy".equals(mood)
{
    System.out.println("IM HAPPYYYYYYY!!!!");
}
于 2013-11-07T03:02:33.593 回答
1

首先,看起来您正在处理错误的变量sc。我想你的意思是比较mood

处理字符串时,请始终使用.equals(),而不是====比较参考,这通常是不可靠.equals()的,同时比较实际值。

将字符串转换为全部大写或全部小写也是一种好习惯。在此示例中,我将使用小写字母.toLowerCase().equalsIgnoreCase()也是解决任何案例问题的另一种快速方法。

我还推荐一个if-else-statement,而不是第二个if-statement。您的代码如下所示:

mood=mood.toLowerCase()

if (mood.equals("happy")) {
    System.out.println("test");
}

else if (mood.equals("sad")) {
    System.out.println("I am sad");

}

这些都是非常基本的 Java 概念,因此我建议您更彻底地阅读其中的一些概念。您可以在此处查看一些文档和/或其他问题:

于 2013-11-07T03:02:51.943 回答
0

您需要更正以下事项:

  1. single =表示赋值,而不是比较。

  2. 我假设您想检查输入的字符串是否等于“快乐”和“悲伤”。使用equals方法而不是“==”来检查字符串值。

  3. 为什么你把 if (sc = sad) 放在 if (sc = happy) 里面。内部检查永远不会执行。

  4. 您需要检查从控制台输入的值,而不是使用 Scanner sc 本身。

所以我认为你需要更改代码如下:

字符串心情 = sc.nextLine();

    if (mood.equals("happy")) {
        System.out.println("test");
    }

    if (mood.equals("sad")) {
        System.out.println("I am sad");
    } 
于 2013-11-07T03:08:17.843 回答