我有4个字符串s1,s2,s3,s4。我想把它与“是”,“否”和“两者”进行比较
它必须像(s1.equals("yes"));
如何进行比较?
答案 0 :(得分:7)
我会将这些字符串存储在列表中,并使用Collections
实用程序查找yes
和no
的频率。然后将您的条件应用于yes
和no
的数量: -
List<String> list = new ArrayList<String>() {{
add("yes"); add("yes"); add("no"); add("no");
}};
int yes = Collections.frequency(list, "yes");
int no = Collections.frequency(list, "no");
if (yes == 4 || yes == 0) { // all "yes" or all "no"
System.out.println("Operation 1");
} else if (yes == 2) { // 2 "yes" and 2 "no"
System.out.println("Operation 2");
} else { // (1 "yes", 3 "no") or (1 "no", 3 "yes")
System.out.println("Operation 3");
}
当然,我认为您的字符串只能是"yes"
或"no"
。
答案 1 :(得分:0)
您可以尝试这种逻辑。这个做了你打算做的事情:
if(s1.equals("yes") && s2.equals("yes") && s3.equals("yes") && s4.equals("yes"))
result1;
else if (s1.equals("no") && s2.equals("no") && s3.equals("no") && s4.equals("no"))
result2;
else if ((s1.equals("yes") || s2.equals("yes")) && (s3.equals("no") || s4.equals("no")))
result3;
else if((s1.equals("yes") || s2.equals("yes") || s3.equals("yes")) && s4.equals("no"))
result4;
else if((s1.equals("no") || s2.equals("no") || s3.equals("no")) && s4.equals("yes"))
result5;
答案 2 :(得分:0)
假设它们是“是”或“否”,请使用:
int yesCount = (s1+s2+s3+s4).replace("no", "").length() / 3;
然后将您的逻辑基于此,可能使用switch(yesCount)
答案 3 :(得分:0)
String[] str={s1,s2,s3,s4};
int yesCount=0, noCount=0;
for(int i=0;i<str.length();i++){
if("yes".equals(str[i]))
yescount++;
else if("no".equals(str[i]))
noCount++;
}
String check=""+yesCount+noCount;
switch(check){
case "40":
//do whatever
break;
case "30":
//do whatever
break;
case "20":
//do whatever
break;
case "10":
//do whatever
break;
case "31":
//do whatever
break;
case "21":
//do whatever
break;
case "11":
//do whatever
break;
case "22":
//do whatever
break;
case "12":
//do whatever
break;
case "13":
//do whatever
break;
case "04":
//do whatever
break;
case "00":
//do whatever
break;
}
答案 4 :(得分:0)
假设字符串值可以是yes或no
int result = 0;
if("yes".equalsIgnoreCase(s0)) result++;
if("yes".equalsIgnoreCase(s1)) result++;
if("yes".equalsIgnoreCase(s2)) result++;
if("yes".equalsIgnoreCase(s3)) result++;
switch(result){
case 0:
System.out.println("all strings are NO");
break;
case 1:
System.out.println("3 strings are NO, 1 string is YES");
break;
case 2:
System.out.println("2 strings are NO, 2 strings are YES");
break;
case 3:
System.out.println("1 string is NO, 3 strings are YES");
break;
case 4:
System.out.println("all strings are YES");
break;
}