2014-02-09 29 views
-1

我正在编写一个程序,需要用户输入并根据他们的答案给他们一个不同的答案。如何使用用户使用if - else语句输入的字符串?字符串如果 - 在Java中的其他语句

我有这个至今:

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语句。

+0

你在网上查找“if语法java”吗?为什么不尝试编译这个? –

+0

结帐这个真棒帖子 http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java –

回答

0

equals

改变这种plant == "Asparagus"

plant.equals("Asparagus") 

比较equals();

0

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

在这种情况下,等号运算符的作用是在字符串变量plant与它为该行分配的新String对象之间进行比较,"Asparagus"。当然,因为它们是不同的对象,它们永远不会平等。

0

“==” - >仅仅是指针的比较讨论(对象引用)

“s1.equals(S2)” - >是内容

1

==操作者在Java中的检查的比较讨论那两个引用是相同的。另一方面,equals(Object)检查两个参考是等于

在你的情况,但也不能保证该字符串Asparagus从用户和硬编码在你的代码,其实是同一个对象的文字,所以==是错误的,你应该使用equals(Object) inputed:

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