【问题标题】:Strings in If - Else Statements in Java [duplicate]If中的字符串-Java中的Else语句[重复]
【发布时间】:2014-02-09 15:55:14
【问题描述】:

我正在编写一个程序,该程序接受用户输入,并根据他们的回答给出不同的答案。如何使用用户通过 if - else 语句输入的字符串?

到目前为止我有这个:

import java.io.*;
import static java.lang.System.*;

import java.util.Scanner;

class t1_lesson07_template{

     public static void main (String str[]) throws IOException {

              Scanner scan = new Scanner(System.in);

              System.out.print("Hello, welcome to the companion planting guide. ");
              System.out.print("Lets get started! To begin, just input the desired plant in the box to learn what plants to grow with it!");
              String plant = scan.nextLine();
              if (plant == "Asparagus") {
                System.out.print("Tomatoes, parsley, and basil.");
              }


     }

}

我想知道在这种情况下 if 语句的语法。

【问题讨论】:

标签: java if-statement syntax statements


【解决方案1】:

Java 中的== 运算符检查两个引用是否相同。另一方面,equals(Object) 检查两个引用是否相等

在你的情况下,不能保证用户输入的字符串Asparagus和你代码中的硬编码文字实际上是同一个对象,所以==是错误的,你应该使用equals(Object):

if (plant.equals("Asparagus")) {
    System.out.print("Tomatoes, parsley, and basil.");
}

【讨论】:

    【解决方案2】:

    equals

    更改此plant == "Asparagus"

    plant.equals("Asparagus")
    

    将字符串与equals();进行比较

    【讨论】:

      【解决方案3】:

      Strings 是 Java 中的对象。很容易将其误认为是原语,因为它是“默认”java.lang 类的一部分。要比较字符串(与所有对象一样),您需要使用 .equals 方法。

      在这种情况下,相等运算符所做的是比较字符串变量plant 的地址和它为该行分配的新字符串对象"Asparagus"。当然,由于它们是不同的对象,它们永远不会相等。

      【讨论】:

        【解决方案4】:

        "==" -> 只是指针的比较(对象引用)

        "s1.equals(s2)" -> 是内容的比较

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-09
          • 1970-01-01
          • 1970-01-01
          • 2017-11-21
          • 1970-01-01
          • 2012-12-06
          • 1970-01-01
          • 2013-07-23
          相关资源
          最近更新 更多