如何比较java中的字符串

我有一个我正在制作的程序,当用户输入心情时,它会根据它输出报价。 我需要告诉程序
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"); } } } } 

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

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

将字符串转换为全部大写或全部小写也是一种好习惯。 我将使用.toLowerCase()在此示例中使用.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概念,所以我建议你仔细阅读其中的一些概念。 您可以在此处查看一些文档和/或其他问题:

  • if-else语句
  • 字符串
  • Java String.equals与==

不能比较像这样的字符串

 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 } 

另外,如果在将来,你需要使用=操作进行比较(对于除字符串之外的任何东西),你会使用double ==

始终使用.equals(..)方法来比较String值。

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

它应该是这样的

  if ("happy".equals(mood) { System.out.println("IM HAPPYYYYYYY!!!!"); } 

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

  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"); } 

您需要更正以下内容:

  1. single =表示分配,而不是比较。

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

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

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

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

String mood = sc.nextLine();

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