求编一道Java程序题目..很急..

2025-03-03 20:15:57
推荐回答(1个)
回答1:

public class Think {
/* 题目:
* 甲乙丙三个小朋友的手里各有一些杏核。
* 甲说:我有12粒,比乙少2粒,比丙多1粒。
* 乙说:我手里的杏核在三人中不是最少。丙和我相差3粒,丙有15粒。
* 丙说:我的杏核比甲少,甲有13粒,乙比甲少2粒。
* 每个小朋友都说了2句真话1句假话。请编写一个程序确定三人的杏核数。
* */
private int max = 1000;//假设小朋友手里最多能抓1000粒杏核,够大了吧~~呵呵

private int x;//甲的杏核数
private int y;//乙的杏核数
private int z;//丙的杏核数

private boolean[] b1 = new boolean[3];
private boolean[] b2 = new boolean[3];
private boolean[] b3 = new boolean[3];

public Think() {
super();

}

private void jugement(){
this.b1[0] = (x==12);
this.b1[1] = ((x+2)==y);
this.b1[2] = ((x-1)==z);

this.b2[0] = ((y>x)||(y>z));
this.b2[1] = ((y==(z+3))||(y==(z-3)));
this.b2[2] = (z==15);

this.b3[0] = (x>z);
this.b3[1] = (x==13);
this.b3[2] = (x==(y+2));
}

private boolean validate(){
boolean result = false;
boolean r1 = (b1[0]==true&&b1[1]==true&&b1[2]==false)
||(b1[0]==true&&b1[1]==false&&b1[2]==true)
||(b1[0]==false&&b1[1]==true&&b1[2]==true);
boolean r2 = (b2[0]==true&&b2[1]==true&&b2[2]==false)
||(b2[0]==true&&b1[1]==false&&b2[2]==true)
||(b2[0]==false&&b2[1]==true&&b2[2]==true);
boolean r3 = (b3[0]==true&&b3[1]==true&&b3[2]==false)
||(b3[0]==true&&b3[1]==false&&b3[2]==true)
||(b3[0]==false&&b3[1]==true&&b3[2]==true);
result = r1&&r2&&r3;
return result;
}

private boolean compute(){
for(this.x=0;this.x<=max;this.x++){
for(this.y=0;this.y<=max;this.y++){
for(this.z=0;this.z<=max;this.z++){
this.jugement();
if(this.validate()){
if(this.x>0&&this.y>0&&this.z>0){
if(this.x!=1000&&this.y!=1000&&this.z!=1000){
return true;
}
}
}
}
}
}
return false;
}

public void getResult(){
if(this.compute()){
System.out.println("甲小朋友手中有"+this.x+"粒杏核");
System.out.println("乙小朋友手中有"+this.y+"粒杏核");
System.out.println("丙小朋友手中有"+this.z+"粒杏核");
}else{
System.out.println("此题无解!,至少是不符合现实情况!");
}
}

public static void main(String[] args) {
Think think = new Think();
think.getResult();
}

}

/*
程序运行结果为:
----------------------------------
*甲小朋友手中有13粒杏核
*乙小朋友手中有15粒杏核
*丙小朋友手中有12粒杏核
**/