gpt4 book ai didi

java - 在 if 语句中使用字符串数组的值

转载 作者:太空宇宙 更新时间:2023-11-04 06:17:47 26 4
gpt4 key购买 nike

在这种情况下,如果用户输入数组 fruits 中可用的任何一个值,我希望 if 语句为 true,但我不明白如何实现这一点。

import java.util.Scanner;

public class Strings {

public static void main(String[] args) {


Scanner Scan = new Scanner(System.in);
String[] fruits = {"Apple", "apple", "Banana", "banana", "Orange", "orange"};

System.out.println("Enter a name of a fruit: ");
String input = Scan.nextLine();
if(/*input = any one of the values in Array fruits*/){
System.out.println("Yes, that's a fruit");
}
else{
System.out.println("No, that's not a fruit.");
}

最佳答案

实现此目的的最简单方法是将数组转换为 List 并使用 contains 方法:

List<String> fruits =
Arrays.asList("Apple", "apple", "Banana", "banana", "Orange", "orange");

System.out.println("Enter a name of a fruit: ");
String input = Scan.nextLine();
if(fruits.contains(input) {
System.out.println("Yes, that's a fruit");
}
else{
System.out.println("No, that's not a fruit.");
}

但是,这可能会带来相当糟糕的性能。将其转换为 HashSet 应该可以解决这个问题:

Set<String> fruits = 
new HashSet<>(Arrays.asList("Apple", "apple", "Banana", "banana", "Orange", "orange"));
// rest of the code unchanged

关于java - 在 if 语句中使用字符串数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27860894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com