简单的鸡兔同笼问题,算法没错,能运行,就是运行时会出问题,老是在判断的地方出错,
每次输入头的个数时,不管输的数字是否满足要求,都会执行head里的if判断,输入腿的个数时也是一样,不管对错都会执行if判断。求大神指点,不胜感激!
import java.util.*;
public class ChickenAndRabbit {
int head=0;
int leg=0;
int temp=0;
public void Head(){
//判断头的个数是否小于零
if(head<=0){
Scanner sc=new Scanner(System.in);
System.out.print("头的个数输入有误,应为正整数,请输入头的个数:");
head=sc.nextInt();
}
}
public void Leg(){
//判断腿的个数是否为奇数
if(leg%2==1){
Scanner cs=new Scanner(System.in);
System.out.print("输入的脚的个数有误,应输入偶数,请输入脚的个数:");
leg=cs.nextInt();
}
//判断腿的个数是否小于零
if(leg<=0){
Scanner cs=new Scanner(System.in);
System.out.print("脚的个数输入有误,应为正偶数,请输入脚的个数:");
leg=cs.nextInt();
}
if(leg<head){
Scanner cs=new Scanner(System.in);
System.out.print("脚的个数输入有误,应大于头的个数,请输入脚的个数:");
leg=cs.nextInt();
}
}
public static void main(String[] args) {
int chicken;
int rabbit;
int head;
int leg;
System.out.print("请输入头的个数:");
Scanner sc=new Scanner(System.in);
head=sc.nextInt();
ChickenAndRabbit h=new ChickenAndRabbit();
h.Head();
System.out.print("请输入脚的个数:");
Scanner cs=new Scanner(System.in);
leg=cs.nextInt();
ChickenAndRabbit l=new ChickenAndRabbit();
l.Leg();
//引入Head方法判断
//引入Leg方法判断
//计算语句
rabbit=(leg-2*head)/2;
chicken=head-rabbit;
System.out.println("鸡的个数是:"+chicken);
System.out.println("兔的个数是:"+rabbit);
}
}
每次输入头的个数时,不管输的数字是否满足要求,都会执行head里的if判断,输入腿的个数时也是一样,不管对错都会执行if判断。求大神指点,不胜感激!
import java.util.*;
public class ChickenAndRabbit {
int head=0;
int leg=0;
int temp=0;
public void Head(){
//判断头的个数是否小于零
if(head<=0){
Scanner sc=new Scanner(System.in);
System.out.print("头的个数输入有误,应为正整数,请输入头的个数:");
head=sc.nextInt();
}
}
public void Leg(){
//判断腿的个数是否为奇数
if(leg%2==1){
Scanner cs=new Scanner(System.in);
System.out.print("输入的脚的个数有误,应输入偶数,请输入脚的个数:");
leg=cs.nextInt();
}
//判断腿的个数是否小于零
if(leg<=0){
Scanner cs=new Scanner(System.in);
System.out.print("脚的个数输入有误,应为正偶数,请输入脚的个数:");
leg=cs.nextInt();
}
if(leg<head){
Scanner cs=new Scanner(System.in);
System.out.print("脚的个数输入有误,应大于头的个数,请输入脚的个数:");
leg=cs.nextInt();
}
}
public static void main(String[] args) {
int chicken;
int rabbit;
int head;
int leg;
System.out.print("请输入头的个数:");
Scanner sc=new Scanner(System.in);
head=sc.nextInt();
ChickenAndRabbit h=new ChickenAndRabbit();
h.Head();
System.out.print("请输入脚的个数:");
Scanner cs=new Scanner(System.in);
leg=cs.nextInt();
ChickenAndRabbit l=new ChickenAndRabbit();
l.Leg();
//引入Head方法判断
//引入Leg方法判断
//计算语句
rabbit=(leg-2*head)/2;
chicken=head-rabbit;
System.out.println("鸡的个数是:"+chicken);
System.out.println("兔的个数是:"+rabbit);
}
}