JAVA逻辑编程题,真心做不出来,麻烦大家了
A、B、C、D、E五位同学各自从不同的途径打听到获得通讯赛第一名的同学的情况:A:姓李,女同学,年龄13,广东人
B:姓张,男同学,年龄11,湖南人
C:姓陈,女同学,年龄13,广东人
D:姓黄,男同学,年龄11,广西人
E:姓张,男同学,年龄12,广东人
实际上,获得第一名的同学姓什么,性别,年龄,哪里人这四项情况在表中已有,但五位同学所打听到的情况,每人仅有一项是正确的。
请根据此推断获得第一名的同学的情况。
import java.util.*; public class FirstStudent { private static String[] infoArray = { "姓李,女同学,年龄13,广东人", // A "姓张,男同学,年龄11,湖南人", // B "姓陈,女同学,年龄13,广东人", // C "姓黄,男同学,年龄11,广西人", // D "姓张,男同学,年龄12,广东人", // E }; // InfoSet private static Set<String> nameSet = new TreeSet<>(); private static Set<String> sex_Set = new TreeSet<>(); private static Set<String> age_Set = new TreeSet<>(); private static Set<String> homeSet = new TreeSet<>(); public static void main(String[] args) { for (String infoString : infoArray) { initInfoSet(infoString); } for (String name : nameSet) { for (String sex : sex_Set) { for (String age : age_Set) { for (String home : homeSet) { if(meetCondition(name, sex, age, home, infoArray[0], 0) && meetCondition(name, sex, age, home, infoArray[1], 0) && meetCondition(name, sex, age, home, infoArray[2], 0) && meetCondition(name, sex, age, home, infoArray[3], 0) && meetCondition(name, sex, age, home, infoArray[4], 0)) { System.out.println( "第一名的同学:" + name + "," + sex + "," + age + "," + home); } } } } } } private static void initInfoSet(String infoString) { nameSet.add(infoString.split(",")[0]); sex_Set.add(infoString.split(",")[1]); age_Set.add(infoString.split(",")[2]); homeSet.add(infoString.split(",")[3]); } private static boolean meetCondition( String nameString, String sex_String, String age_String, String homeString, String infoString, int meetTimes) { meetTimes = nameString.equals(infoString.split(",")[0]) ? meetTimes + 1 : meetTimes; meetTimes = sex_String.equals(infoString.split(",")[1]) ? meetTimes + 1 : meetTimes; meetTimes = age_String.equals(infoString.split(",")[2]) ? meetTimes + 1 : meetTimes; meetTimes = homeString.equals(infoString.split(",")[3]) ? meetTimes + 1 : meetTimes; return (meetTimes == 1); // 每人仅有一项是正确的 } }