Где ошибки в моем коде на основе результата запуска? [закрыто]JAVA

Программисты JAVA общаются здесь
Anonymous
Где ошибки в моем коде на основе результата запуска? [закрыто]

Сообщение Anonymous »

Я работаю над заданием Java (запуск в системе VPL), которая реализует классы: BinaryNumber , BinaryRepresentation и bit . Назначение включает в себя арифметические операции, такие как добавление, вычитание, умножение, разделение и tointstring () на двоичных числах. У меня нет доступа к полным входам, так как они скрыты, но я получаю следующий вывод от Test Runner: < /p>
SanityTests.runTest_subtract_5P ... failed -> 0 Points because
The function subtract should not throw an exception of type "IllegalArgumentException" for the input: 5 - 3, 3 - 5

SanityTests.runTest_divide_5P ... failed -> 0 Points because
Wrong result for -9 / 3 expected: but was:

SanityTests.runTest_toIntString_10P ... failed -> 0 Points because
The function toIntString should not throw an exception of type "RuntimeException"
for the input: 354224848179261915075
checking 2.5:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal Number
at BinaryNumber.toString(BinaryNumber.java:315)

checking 2.11:
fail: Input 3 and 1 should be 3 but yours is: 0
fail: Input 8 and 5 should be 1 but yours is: 0
fail: Input 16 and 3 should be 5 but yours is: 0
fail: Input 108 and 16 should be 6 but yours is: 0
fail: Input 1600 and 57 should be 28 but yours is: 0

checking 2.13:
Exception in thread "main" java.lang.RuntimeException: Number is bigger or smaller than max int value!
at BinaryNumber.toInt(BinaryNumber.java:365)

Почему subtract () выбрасывает исключение для простых случаев, таких как 5 - 3 или 3 - 5 ? /> Код компилирует и проходит другие тесты, но эти конкретные части вызывают сбои. Файлы)
Нет доступа к Источникам тестового класса
Классы I Реализуйте: Binarynumber , BinaryRepresentation , bit .
Любые у признания отладки или исправить эти проблемы.
> здесь:/(/> > здесь:/(/> > здесь:/(/> > здесь:/код.import java.util.Iterator;

public class BinaryNumber implements Comparable {
final private BinaryRepresentation rep;

public BinaryNumber(int n) {
this.rep = new BinaryRepresentation();
if (n == 0) {
rep.addLast(Bit.ZERO);
return;
}
boolean isNegative = n < 0;
n = Math.abs(n);
while (n > 0) {
int bit = n % 2;
rep.addLast(Bit.of(bit));
n = n / 2;
}
rep.addLast(isNegative ? Bit.ONE : Bit.ZERO);
}

public BinaryNumber(BinaryNumber other) {
this.rep = new BinaryRepresentation(other.rep);
}

public BinaryNumber(String s) {
BinaryNumber ans = new BinaryNumber(0);
boolean isNeg = false;
int i = 0;
if (s.charAt(i) == '-') {
isNeg = true;
i++;
}
int toAdd;
while (i < s.length()) {
toAdd = charToInt(s.charAt(i));
ans = ans.multiply(new BinaryNumber(10));
ans = ans.add(new BinaryNumber(toAdd));
i++;
}
if (isNeg) {
ans = ans.negate();
}
this.rep = ans.rep;
}

private int charToInt(char a) {
return "0123456789".indexOf(a);
}

public BinaryNumber add(BinaryNumber other) {
if (other == null) {
return null;
}
BinaryNumber result = new BinaryNumber(0);
result.rep.removeLast();
BinaryRepresentation thisRep = new BinaryRepresentation(this.rep);
BinaryRepresentation otherRep = new BinaryRepresentation(other.rep);
int maxLength = Math.max(this.length(), other.length());
thisRep.padding(maxLength + 1);
otherRep.padding(maxLength + 1);
Iterator thisIter = thisRep.iterator();
Iterator otherIter = otherRep.iterator();
Bit carry = Bit.ZERO;
while (thisIter.hasNext() && otherIter.hasNext()) {
Bit currthis = thisIter.next();
Bit currother = otherIter.next();
result.rep.addLast(Bit.fullAdderSum(currthis, currother, carry));
carry = Bit.fullAdderCarry(currthis, currother, carry);
}
result.rep.reduce();
return result;
}

public BinaryNumber negate() {
BinaryNumber copy = new BinaryNumber(this);
copy.rep.complement();
BinaryNumber one = new BinaryNumber(1);
BinaryNumber result = copy.add(one);
if (result != null) {
result.rep.reduce();
}
return result;
}

public BinaryNumber subtract(BinaryNumber other) {
if (other == null) {
return new BinaryNumber(0);
}
BinaryNumber result = this.add(other.negate());
result.rep.reduce();
return result;
}

public int signum() {
if (this.rep.getNumOfOnes() == 0) {
return 0;
} else if (this.rep.getLast().equals(Bit.ZERO)) {
return 1;
}
return -1;
}

private BinaryNumber multiplyPositive(BinaryNumber other) {
BinaryNumber copyThis = new BinaryNumber(this);
BinaryNumber copyOther = new BinaryNumber(other);
BinaryNumber ans = new BinaryNumber(0);
Iterator otherIter = copyOther.rep.iterator();
while (otherIter.hasNext()) {
if (otherIter.next().equals(Bit.ONE)) {
ans = ans.add(copyThis);
}
copyThis = copyThis.multiplyBy2();
}
return ans;
}

public BinaryNumber multiply(BinaryNumber other) {
BinaryNumber copyThis = new BinaryNumber(this);
BinaryNumber copyOther = new BinaryNumber(other);
boolean shouldFlip = false;
if (copyOther.signum() == -1 && copyThis.signum() == -1) {
copyOther = copyOther.negate();
copyThis = copyThis.negate();
} else if (copyOther.signum() == -1) {
copyOther = copyOther.negate();
shouldFlip = true;
} else if (copyThis.signum() == -1) {
copyThis = copyThis.negate();
shouldFlip = true;
}
BinaryNumber ans = copyThis.multiplyPositive(copyOther);
if (shouldFlip) {
ans = ans.negate();
}
return ans;
}

public BinaryNumber divide(BinaryNumber other) {
if (other == null || other.signum() == 0) {
throw new IllegalArgumentException("the divisor is 0 or null");
}
boolean negResult = (this.signum() < 0) ^ (other.signum() < 0);
BinaryNumber dividend = this.signum() < 0 ? this.negate() : this;
BinaryNumber divisor = other.signum() < 0 ? other.negate() : other;
BinaryNumber quotient = dividend.dividePositive(divisor);
if (negResult) {
quotient = quotient.negate();
}
quotient.rep.reduce();
return quotient;
}

private BinaryNumber dividePositive(BinaryNumber other) {
BinaryNumber remainder = new BinaryNumber(0);
BinaryNumber quotient = new BinaryNumber(0);
quotient.rep.removeLast();
int n = this.length();
for (int i = n - 1; i >= 0; i--) {
remainder.rep.shiftLeft();
remainder.rep.removeFirst();
remainder.rep.addLast(this.rep.getFirst());
if (remainder.compareTo(other) >= 0) {
remainder = remainder.subtract(other);
quotient.rep.addFirst(Bit.ONE);
} else {
quotient.rep.addFirst(Bit.ZERO);
}
}
quotient.rep.reduce();
return quotient;
}

public String toString() {
if (!isLegal()) {
throw new IllegalArgumentException("Illegal Number");
}
String result = "";
Bit[] bitsArray = new Bit[rep.length()];
int index = 0;
for (Bit bit : rep) {
bitsArray[index++] = bit;
}
for (int i = bitsArray.length - 1; i >= 0; i--) {
result += bitsArray.toString();
}
return result;
}

public boolean equals(Object other) {
if (!(other instanceof BinaryNumber)) {
return false;
}
BinaryNumber otherBinary = (BinaryNumber) other;
return this.toString().equals(otherBinary.toString());
}

public int compareTo(BinaryNumber other) {
BinaryNumber result = this.subtract(other);
int ans = result.signum();
return ans;
}

public int toInt() {
int output = 0;
int multiply = 1;
boolean isNeg = false;
BinaryNumber temp = new BinaryNumber(this);
if (this.signum() == -1) {
temp = temp.negate();
isNeg = true;
}
Iterator bitIterator = temp.rep.iterator();
Bit currentBit = Bit.of(0);
while (bitIterator.hasNext()) {
currentBit = bitIterator.next();
if (output > Integer.MAX_VALUE / multiply || output < Integer.MIN_VALUE / multiply) {
throw new RuntimeException("Number is bigger or smaller than max int value!");
}
output = output + currentBit.toInt() * multiply;
multiply = multiply * 2;
}
if (isNeg) {
output = -output;
}
return output;
}

public String toIntString() {
if (!isLegal()) {
throw new IllegalArgumentException("Illegal Number");
}
if (this.signum() == 0) {
return "0";
} else {
BinaryNumber temp = new BinaryNumber(this);
BinaryNumber baseTen = new BinaryNumber(10);
String ans = "";
if (this.signum() < 0) {
ans += "-";
temp = temp.negate();
}
while (!temp.equals(new BinaryNumber(0))) {
BinaryNumber div = temp.divide(baseTen);
int toAdd = (temp.subtract(div.multiply(baseTen))).toInt();
ans = ans + toAdd;
temp = div;
}
return ans;
}
}

public boolean isLegal() {
return rep.isLegalNumber() && rep.isReduced();
}

public int length() {
return this.rep.length();
}

private BinaryNumber multiplyBy2() {
BinaryNumber res = new BinaryNumber(this);
res.rep.shiftLeft();
return res;
}

private BinaryNumber divideBy2() {
BinaryNumber res = new BinaryNumber(this);
res.rep.shiftRight();
return res;
}
}
import java.util.Iterator;
import java.util.LinkedList;

public class BinaryRepresentation implements Iterable {
final private LinkedList bits;
private int numOfOnes;

public BinaryRepresentation() {
this.bits = new LinkedList();
this.numOfOnes = 0;
}

public BinaryRepresentation(BinaryRepresentation other) {
this.bits = new LinkedList();
this.numOfOnes = 0;
for (Bit bit : other.bits) {
this.bits.addLast(bit);
if (bit.equals(Bit.ONE)) {
this.numOfOnes++;
}
}
}

public void addFirst(Bit bit) {
if (bit == null) {
throw new IllegalArgumentException("Bit cannot be null");
}
this.bits.addFirst(bit);
if (bit.equals(Bit.ONE)) {
numOfOnes++;
}
}

public void addLast(Bit bit) {
if (bit == null) {
throw new IllegalArgumentException("Bit cannot be null");
}
this.bits.addLast(bit);
if (bit.equals(Bit.ONE)) {
numOfOnes++;
}
}

public Bit removeFirst() {
Bit removed = this.bits.removeFirst();
if (removed.equals(Bit.ONE)) {
numOfOnes--;
}
return removed;
}

public Bit removeLast() {
Bit removed = this.bits.removeLast();
if (removed.equals(Bit.ONE)) {
numOfOnes--;
}
return removed;
}

public boolean isLegalNumber() {
if (length() == 0) {
return false;
}
if (length() == 1) {
return getFirst().equals(Bit.ZERO);
}
Bit msb = getLast();
if (msb.equals(Bit.ZERO)) {
return true;
}
return numOfOnes > 1;
}

public boolean isReduced() {
if (!isLegalNumber()) {
return false;
}
if (length() == 1) {
return true;
}
Bit msb = getLast();
Bit secondMSB = bits.get(length() - 2);
return !msb.equals(secondMSB);
}

public void reduce() {
boolean done = false;
while (!done && length() > 1) {
Bit msb = getLast();
Bit secondMSB = bits.get(length() - 2);
if (msb.equals(secondMSB)) {
removeLast();
if (!isLegalNumber()) {
addLast(msb);
done = true;
}
} else {
done = true;
}
}
}

public void complement() {
for (int i = 0; i < bits.size(); i++) {
Bit original = bits.get(i);
Bit negated = original.negate();
bits.set(i, negated);
}

numOfOnes = 0;
for (Bit bit : bits) {
if (bit.equals(Bit.ONE)) {
numOfOnes++;
}
}
}

public void shiftLeft() {
addFirst(Bit.ZERO);
}

public Bit shiftRight() {
if (length() == 0) {
return null;
}
return removeFirst();
}

public void padding(int newLength) {
while (length() < newLength) {
addLast(getLast());
}
}

public String toString() {
String result = "";
return result;
}

public Bit getLast() {
return this.bits.get(this.bits.size() - 1);
}

public Bit getFirst() {
return this.bits.get(0);
}

public int getNumOfOnes() {
return this.numOfOnes;
}

public int length() {
return this.bits.size();
}

public Iterator iterator() {
return this.bits.iterator();
}
}
final public class Bit implements Comparable {
public static final Bit ONE = new Bit(true);
public static final Bit ZERO = new Bit(false);

private final boolean value;

private Bit(boolean value) {
this.value = value;
}

public static Bit of(boolean value) {
if (value) {
return ONE;
}
return ZERO;
}

public static Bit of(int intValue) {
if (intValue != 0 && intValue != 1) {
throw new IllegalArgumentException(intValue + " is neither 0 nor 1.");
}
if (intValue == 1) {
return ONE;
}
return ZERO;
}

public int toInt() {
if (value) {
return 1;
}
return 0;
}

public boolean toBoolean() {
return value;
}

public String toString() {
if (value) {
return "1";
}
return "0";
}

public boolean equals(Object obj) {
return this == obj;
}

public int compareTo(Bit other) {
return Boolean.compare(this.value, other.value);
}

public Bit negate() {
if (this.value) {
return Bit.ZERO;
}
return Bit.ONE;
}

public static Bit fullAdderSum(Bit bit1, Bit bit2, Bit bit3) {
if (bit1.value ^ bit2.value ^ bit3.value) {
return ONE;
}
return ZERO;
}

public static Bit fullAdderCarry(Bit bit1, Bit bit2, Bit bit3) {
if (((bit1.value ^ bit2.value) && bit3.value) || (bit1.value && bit2.value)) {
return ONE;
}
return ZERO;
}
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... run-result

Вернуться в «JAVA»