如何使用扫描程序检查数组中的字符串值

时间:2017-11-21 12:27:59

标签: java arrays java.util.scanner

我对编程很陌生,但我无法弄清楚如何使用字符串扫描程序查看它是否存在于数组中(如果数组包含“Apple”而扫描程序返回“Apple”,“打印”当下”)。我正在使用Eclipse Mars 4.5.0,我到目前为止的代码如下:

public static void main(String[] args) {


    String answer = "null"; //Initialize "answer"
    String[] Fruit;         //Array of Strings called "Fruit"
    Fruit = new String[10]; //"Fruit" has 10 spaces
    //Strings saved in "Fruit":
    Fruit[0] = "Apple";
    Fruit[1] = "Banana";
    Fruit[2] = "Mango";
    Fruit[3] = "Pear";

    //The actual programme:
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter a fruit:");
    answer = input.next();
                                                            //If the answer is 'Fruit[0]'
    if (answer == Fruit[0] || answer == Fruit[1] ||         //OR 'Fruit[1]' OR etc,
        answer == Fruit[2] || answer == Fruit[3]) {         //Print "available"
        System.out.println("This fruit is available.");
    }
                                                            //If the answer isn't 'Fruit[0]'
    else if (answer != Fruit[0] && answer != Fruit[1] &&    // AND not 'Fruit[1]' AND not
            answer != Fruit[2] && answer != Fruit[3]){      //etc, Print "not available"
        System.out.println("This fruit is not available right now.");
    }
}

然而,它总是返回“不可用”,同样适用于While循环:它似乎不会检查它是否存在于Arraylist中。

有人知道如何解决这个问题吗?我很想知道,因为我在互联网上找不到任何类似的问题。

编辑:奇怪的是,我搜索了很多次,猜测我错过了一个,抱歉复制了!

1 个答案:

答案 0 :(得分:0)

而非使用

if (answer == Fruit[0] || answer == Fruit[1] ||         //OR 'Fruit[1]' OR etc,
        answer == Fruit[2] || answer == Fruit[3])

使用:

if (TextUtils.equals(answer,Fruit[0]) || TextUtils.equals(answer,Fruit[1]) ||         
        TextUtils.equals(answer,Fruit[2]) || TextUtils.equals(answer,Fruit[3]))
  

字符串始终与等于方法进行比较,而不是 == 方法