我有一个包含 8 个字符串的数组
(卡特”、“科克”、“华盛顿”、“格林”、“霍金斯”、“约翰逊”、“沙利文”、“尤尼科伊”)
全部由“县”引用
我会提示用户输入 1-8 (iVal) 之间的数字,1 是 Carter,2 是 Cocke,等等...
除了使用 switch 语句之外,还有其他方法可以做到这一点吗?
此外,如果用户输入 Washington,我将显示“Washington is in the array”,如果字符串不在数组中,则显示相反的内容,我该如何处理?
提前致谢。
这是我的数组。
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
for (int i = 0; i< county.length; i++)
{
System.out.print (county [i]+ "\n");
}
最佳答案
提示用户输入一个县,然后显示它(无需开关)非常简单。你可以使用类似的东西,
String[] county = { "Carter", "Cocke", "Washington", "Greene",
"Hawkins", "Johnson", "Sullivan", "Unicoi" };
Scanner scan = new Scanner(System.in);
for (int i = 0; i < county.length; i++) {
System.out.printf("%d %s%n", i + 1, county[i]);
}
System.out.println("Please select a county from above: ");
int choice = scan.nextInt();
if (choice > 0 && choice <= county.length) {
System.out.println("You selected: " + county[choice - 1]);
} else {
System.out.println("Not a valid choice: " + choice);
}
至于测试String
数组是否包含特定的String
,您可以使用 for-each
loop 编写一个实用程序函数喜欢
public static boolean contains(String[] arr, String val) {
if (arr != null) {
for (String str : arr) {
if (str.equals(val)) {
return true;
}
}
}
return false;
}
关于java - 如何显示用户输入的数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007421/