Java 中使用 Switch 循环处理字符串集合
使用 switch 循环一个字符串集合,你可以按照以下方式实现:
List<String> strings = Arrays.asList('abc', 'def', 'ghi');
for (String str : strings) {
switch (str) {
case 'abc':
// 处理'abc'的情况
break;
case 'def':
// 处理'def'的情况
break;
case 'ghi':
// 处理'ghi'的情况
break;
default:
// 处理其他情况
break;
}
}
上述代码首先创建了一个字符串集合strings,然后使用 foreach 循环遍历集合中的每个字符串。在循环体中,使用 switch 语句根据每个字符串的值进行不同的处理。你可以根据实际需求,在 case 语句中编写相应的处理逻辑。在最后的 default 语句中,可以处理其他未在 case 中列出的情况。
原文地址: https://www.cveoy.top/t/topic/pjDG 著作权归作者所有。请勿转载和采集!