我需要创建一种算法,以完成以下工作:
我有一个8位数字;
我想为数字1和2.输入两个随机数,然后让算法完成其余的工作。
简短:
given: d3, d4, d5, d6
input: d1, d2
algorithm:
d7 := d1 + d2 + d3
d8 := d4 + d5 + d6
到目前为止,我已经找到了这种方法,但是方法有问题。有人可以帮忙吗?
public class Number {
private int d1, d2, d3, d4, d5, d6, d7, d8;
public Number(int d3, int d4, int d5, int d6) {
this.d3 = d3;
this.d4 = d4;
this.d5 = d5;
this.d6 = d6;
}
public void algorithm(int d1, int d2) {
this.d1 = d1;
this.d2 = d2;
this.d7 = this.d1 + this.d2 + this.d3;
this.d8 = this.d4 + this.d5 + this.d6;
}
}
答案 0 :(得分:0)
该算法是正确的,只是它不处理无效的输入(即,输入数字或计算出的数字不正确的地方)。除此之外,要运行代码,请在每个Java程序从该方法开始执行时添加public static void main方法。随附示例工作代码供您参考。
public class Number {
private Integer d1, d2, d3, d4, d5, d6, d7, d8;
private boolean isDigit(int digit) {
return digit >= 0 && digit < 10;
}
private boolean isNotDigit(int digit) {
return !isDigit(digit);
}
public Number(int d3, int d4, int d5, int d6) throws IllegalDigitException {
if (isNotDigit(d3) || isNotDigit(d4) || isNotDigit(d5) || isNotDigit(d6))
throw new IllegalDigitException("All entered digits must be positive and less than 10");
this.d3 = d3;
this.d4 = d4;
this.d5 = d5;
this.d6 = d6;
}
public void algorithm(int d1, int d2) throws IllegalDigitException {
if (isNotDigit(d1) || isNotDigit(d2))
throw new IllegalDigitException("All entered digits must be positive and less than 10");
this.d1 = d1;
this.d2 = d2;
this.d7 = this.d1 + this.d2 + this.d3;
this.d8 = this.d4 + this.d5 + this.d6;
if (isNotDigit(d7) || isNotDigit(d8))
throw new IllegalDigitException("All calculated digits must be positive and less than 10, please try with other d1 and d2 values");
}
@Override
public String toString() {
return new Integer(d1.toString() + d2.toString() + d3.toString() + d4.toString() + d5.toString() + d6.toString() + d7.toString() + d8.toString()).toString();
}
public static void main(String[] args) {
Number n = null;
try {
n = new Number(10, 2, 3, 4);
n.algorithm(0, 1);
System.out.println("Number is " + n.toString());
} catch (IllegalDigitException e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
class IllegalDigitException extends Exception {
public IllegalDigitException(String message) {
super(message);
}
}
}