Note that there are some explanatory texts on larger screens.

plurals
  1. POMaking an immutable class
    text
    copied!<p>I'm in the process of trying to make an immutable class in which represents natural numbers. I'm using recursion in order to handle the Increment and Decrement methods. Since the fields are final, I made a private constructor to assign new values to the necessary fields when decrementing/incrementing. After testing this implementation, I can't seem to pin point the problem. If I decrement 100, it will be 10. If I increment 99, it will be 9. If I increment/decrement a number not on the bound, I will get a long string of gibberish. I guess I need a nudge in the right direction. I'm able to get it to work fine if it's mutable because i don't have to worry about the final fields.</p> <pre><code>public final class SlowBigNatural implements BigNatural{ final private int natural[]; final private int nSize; final private int HIGHEST = 9; public SlowBigNatural() { this.nSize = 1; this.natural = new int[1]; this.natural[0] = 0; } public SlowBigNatural(int p) { this(Integer.toString(p)); } public SlowBigNatural(String s) { this.nSize = s.length(); this.natural = new int[nSize]; for (int i = 0; i &lt; nSize; i++) { this.natural[i] = Character.digit(s.charAt(i), 10); } } public SlowBigNatural(BigNatural c) { this(c.toString()); } private SlowBigNatural(int[] natural, int nSize){ this.nSize = nSize - 1; this.natural = new int[this.nSize]; for (int i = 0; i &lt; this.nSize; i++) { this.natural[i] = natural[i]; } } public BigNatural increment() { int[] nClone = new int[nSize]; System.arraycopy(natural, 0, nClone, 0, nSize); if (nSize == 1 || nClone[nSize - 1] != HIGHEST) { nClone[nSize - 1]++; BigNatural nInc = new SlowBigNatural(nClone.toString()); return nInc; } else { nClone[nSize - 1] = 0; BigNatural temp = new SlowBigNatural(nClone, nSize); temp.increment(); return temp; } } public BigNatural decrement() { int[] nClone = natural.clone(); if (nClone[nSize - 1] != 0) { nClone[nSize - 1]--; BigNatural nDec = new SlowBigNatural(nClone.toString()); return nDec; } else { if (nSize != 1) { nClone[nSize - 1] = HIGHEST; BigNatural temp = new SlowBigNatural(nClone, nSize); temp.decrement(); return temp; } else{ BigNatural nDec = new SlowBigNatural(0); return nDec; } } } public String toString() { String nString = ""; for (int i = 0; i &lt; nSize; i++) { nString += String.valueOf(natural[i]); } return nString.replaceFirst("^0+(?!$)", ""); } } </code></pre> <p>I stepped through my code, and the error seems to occur when I convert the array to a string and pass it through the constructor. It turns the array into a bunch of craziness. Continuing to investigate.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload