黑马程序员技术交流社区

标题: 鸡兔同笼问题 [打印本页]

作者: wu971856966    时间: 2016-11-15 21:00
标题: 鸡兔同笼问题
package com.Anli.bean;
/*鸡兔同笼问题,用户输入脚和头,输出鸡有多少,兔有多少。
考虑健壮性的问题,当用户输入有错误的时候应该怎么样提示。
*/
import java.util.Scanner;

public class Jitu {
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                for (int i = 0; i < 3; i++) {
                        System.out.println("请输入头的数量:");
                        int s1 = sc.nextInt();
                        System.out.println("请输入脚的数量:");
                        int s2 = sc.nextInt();
                        if (s1 < 0 || s2 < 0) {
                                System.out.println("你的输入有误!你还有" + (2-i) + "次机会输入");
                               
                        }else {
                                if (s1 == 0 && s2 == 0) {
                                        System.out.println("鸡兔数量为零");
                                        break;
                                }else {
                                        int s3;
                                        int s4;
                                        s3 =(4*s1-s2)/2;
                                        s4 =s1-s3;
                                        if (s3 < 0 || s4<0) {
                                                System.out.println("你的答案有问题请重新输入!");
                                               
                                        }else {
                                                System.out.println("鸡的数量是:" + s3);
                                        System.out.println("兔的数量是:" + s4);
                                                       
                                        break;
                                        }
                                       
                                }
                        }
                }
               
        }
}







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2