如何在java中比较字符串 [英] How to Compare strings in java
问题描述
我有一个程序,我在做的地方,当用户键入的心情,它会输出一个基于它的报价。我需要告诉程序
如果用户满意,然后输出此文本
问题是,我不知道如何获取程序基于它来识别输入和输出文本...这里是我为代码到目前为止。
I have a program I'm making where when the user type in a mood, it will output a quote based on it. I need to tell the program
if the user is happy, then output this text
The problem is, I don't know how to get the program to recognize the input and output the text based on it... here's what I have for code so far.
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
。
First of all, it looks like you are dealing with the wrong variable sc
. I think you meant to compare mood
.
在处理字符串时,总是使用。 equals()
,而不是 ==
。 ==
比较引用,通常不可靠, .equals()
比较实际值。
When dealing with strings, always use .equals()
, not ==
. ==
compares the references, which is often unreliable, while .equals()
compares the actual values.
这也是一个好的做法,将字符串转换为全大写或全小写。在这个例子中,我将使用小写的 .toLowerCase()
。 .equalsIgnoreCase()
也是关于任何案例问题的另一种快速方法。
It's also good practice to either convert your string to all uppercase or all lower case. I'll use lower case in this example with .toLowerCase()
. .equalsIgnoreCase()
is also another quick way around any case problems.
我还推荐一个 if-else语句
,而不是第二个 if -statement
。您的代码将如下所示:
I'd also recommend an if-else-statement
, not a second if-statement
. Your code would look like this:
mood=mood.toLowerCase()
if (mood.equals("happy")) {
System.out.println("test");
}
else if (mood.equals("sad")) {
System.out.println("I am sad");
}
这些都是相当基本的java概念,推荐阅读更多关于其中一些。您可以在这里查看一些文档和/或其他问题:
These are all pretty basic java concepts, so I'd recommend reading more thoroughly about some of them. You can check out some of the documentation and/or other questions here:
- if-else statement
- Strings
- Java String.equals versus ==
这篇关于如何在java中比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!