`
java-mans
  • 浏览: 11439058 次
文章分类
社区版块
存档分类
最新评论

算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;
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics