算4个数 通过加减乘除 结果为24 列举每种情况统计...

package com.hpli.demo;

import javax.swing.JOptionPane;

public class Demo
{
//算4个数 通过加减乘除 结果为24 列举每种情况统计... 得用double型的变量存储数据
public static void main(String args[])
{
int count = 0;
String out = "";
double num1 = 1;
double num2 = 1;
double num3 = 1;
double num4 = 1;

try
{
num1 = Double.parseDouble(JOptionPane.showInputDialog("Please enter the first integer!"));
num2 = Double.parseDouble(JOptionPane.showInputDialog("Please enter the second integer!"));
num3 = Double.parseDouble(JOptionPane.showInputDialog("Please enter the third integer!"));
num4 = Double.parseDouble(JOptionPane.showInputDialog("Please enter the fourth integer!"));
}

catch (NumberFormatException numberFormatException)
{
JOptionPane.showMessageDialog(null,
"You must enter an integer",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}

for (int i = 1; i <= 4; i++)
{
double tmp1 = jiSuan(i, num1, num2);

for (int j = 1; j <= 4; j++)
{
double tmp2 = jiSuan(j, tmp1, num3);

for (int k = 1; k <= 4; k++)
{
double tmp3 = jiSuan(k, tmp2, num4);

if (tmp3 == 24)
{
count++;
out +=
"第" + count + "个解法:((" + (int)num1 + getSign(i) + (int)num2 + ")" + getSign(j) + (int)num3
+ ")" + getSign(k) + (int)num4 + "= 24\n";
}
}
}
}
String outPut = "";
if (count == 0)
{
outPut += "对不起," + (int)num1 + " " + (int)num2 + " " + (int)num3 + " " + (int)num4 + " 算24点无解......";
}
else
{
outPut += "总共" + count + "种解法,它们是:\n" + out;
}

JOptionPane.showMessageDialog(null, outPut, "Result", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}

public static double jiSuan(int a, double b, double c)
{
double number = 0;
switch (a)
{
case 1:
number = b + c;
break;

case 2:
number = b - c;
break;

case 3:
number = b * c;
break;

case 4:
number = b / c;
break;
}
return number;
}

public static String getSign(int a)
{
String sign = "";
switch (a)
{
case 1:
sign = "+";
break;

case 2:
sign = "-";
break;

case 3:
sign = "×";
break;

case 4:
sign = "÷";
break;
}
return sign;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值