结对编程

结对编程练习

1.题目避免重复

2.可定制(数量、打印方式)

3.可以控制参数

 package oper;

import java.util.Scanner;

public class Test {

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        Operation op = new Operation();
        Boolean isFour = false;
        Boolean kh = false;
        
        System.out.println("算式的个数:");
        int count = input.nextInt();
        System.out.println("运算数值上限:");
        int max = input.nextInt();
        System.out.println("是否包含乘、除运算:(1、是  0、否)");
        int four = input.nextInt();
        if(four == 1){
            isFour = true;
        }
        System.out.println("是否包含括号:(1、是  0、否)");
        int k = input.nextInt();
        if(k == 1){
            kh = true;
        }
        op.print(count,max,isFour,kh);
                
    }
}


package oper;

import java.util.Random;

public class Operation {
    
    //输出算式
    public void print(int count,int max,Boolean isFour,Boolean kh){ 
        //count--算式的个数,max--数值上限,isFour--有乘除,kh--有括号
        for(int i = 0;i < count; i++){
            System.out.println(oper(max,isFour,kh));
        }
    }
    
    //生成算式
    public String oper(int max,Boolean isFour,Boolean kh){
        Random rand = new Random();
        String oprt = "";
        oprt += number(max);
        //随机运算符的个数(1~4)
        int count = rand.nextInt(4) + 1;
        if(kh && count > 1){
            int x,y;
            x = rand.nextInt(count - 1);
            y = rand.nextInt(count - x) + x;
            if( y == x){
                y ++;
            }
            for(int i = 0; i < count;i ++){
                oprt += operator(isFour);
                if(i == x){
                    oprt += '(';
                }
                oprt += number(max);
                if(i == y){
                    oprt += ')';
                }
            }
        }else{
            for(int i = 0; i < count ;i ++){
                oprt += operator(isFour);
                oprt += number(max);
            }
        }
            
        return oprt;
    }
    
    //生成随机数
    public int number(int max){//max为最大值,用于确定数值范围
        Random rand = new Random();
        int num;
        num = rand.nextInt(max) + 1;
        return num;
    }
    
    //随机生成运算符
    public char operator(Boolean isFour){//isFour为true则包含乘除,isFour为false则只含加减
        char[] two = {'+','-'}; 
        char[] four = {'+','-','*','/'};
        Random rand = new Random();
        int c;
        if(isFour){
            c = rand.nextInt(4);
            return four[c];
        }else{
            c = rand.nextInt(2);
            return two[c];
        }

    }
    

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值