给定a,b和c,如果其中任何一个可以通过使用其他两个数字的数学运算形成,则返回true。允许的数学运算是加法,减法,乘法和除法。例如if a=12, b = 15, c = 3 output is true (15-12 = 3).
我试图解决这个问题,虽然解决方案大部分时间都有效,但是在'0,0,255'
或类似的情况下它不起作用。
我的代码: -
public class CheckCombination {
static int testcase11 = 0;
static int testcase12 = 0;
static int testcase13 = 512;
public static void main(String args[]){
CheckCombination testInstance = new CheckCombination();
boolean result = testInstance.combine(testcase11,testcase12,testcase13);
System.out.println(result);
}
//write your code here
public boolean combine(int a, int b,int c){
boolean checkComb1 = a==(b/c)||a==(b+c)||a==(b-c)||a==(b*c)||a==(c-b)||a==(c/b);
boolean checkComb2 = b==(a/c)||b==(a+c)||b==(a-c)||b==(c*a)||b==(c-a)||b==(a+c);
boolean checkComb3 = c==(a/b)||c==(b/a)||c==(a-b)||c==(b-a)||c==(a*b)||c==(a+b);
boolean finalCheck = checkComb1||checkComb2||checkComb3;
return finalCheck;
}}
我做错了什么以及哪些改变可以纠正这个问题,或者我只是想错了?
答案 0 :(得分:4)
我认为你的问题是你像以下一样除以零:(a / b)
a=0 and b= 0
因此,您需要检查其中一个参数是否为0,以便您可以猜测其他参数,如:
If one of the parameters = 0, if the others are equal, return true else return false
If two of the parameters = 0, it will return false and doesn't matter what the last value is
If the all parameters = 0, you will return true
答案 1 :(得分:0)
这是零问题而不是NPE。
提示:在进行除法之前,请先检查 DIVISOR 。
此外,您可以通过以下方式改进代码:
public boolean combine(int a, int b, int c) {
boolean check = checkIfOk(a,b,c);
check = checkIfOk(b,a,c);
check = checkIfOk(c,a,b);
return check;
}
public boolean checkIfOk(int a, int b, int c) {
boolean ret = a==(b+c) || a==(b-c) || a==(b*c);
if(c != 0) ret = ret || a==(b/c);
return ret;
}
答案 2 :(得分:0)
你去,只是先用这样的东西检查你的除数
if(testcase11!= 0&& testcase12!= 0&& testcase13!= 0)
答案 3 :(得分:0)
检查分母是否为零,否则除以0异常发生。
公共课测试{
static int testcase11 = 0;
static int testcase12 = 0;
static int testcase13 = 512;
public static void main(String args[]){
Test testInstance = new Test();
boolean result = testInstance.combine(testcase11,testcase12,testcase13);
System.out.println(result);
}
//write your code here
public boolean combine(int a, int b,int c){
boolean checkComb1 = (c!=0)?a==(b/c):false||a==(b+c)||a==(b-c)||a==(b*c)||a==(c-b)||(b!=0)?a==(c/b):false;
boolean checkComb2 = (c!=0)?b==(a/c):false||b==(a+c)||b==(a-c)||b==(c*a)||b==(c-a)||b==(a+c);
boolean checkComb3 = (b!=0)?c==(a/b):false||(a!=0)?c==(b/a):false||c==(a-b)||c==(b-a)||c==(a*b)||c==(a+b);
boolean finalCheck = checkComb1||checkComb2||checkComb3;
返回finalCheck; }}