- Numbers Won't Increment
- public class TestBigNaturalSimple {
- public static void main(String[] args) {
- BigNatural b1 = new BigNatural(); // default constructor
- BigNatural b2 = new BigNatural(23); // one-argument int constructor
- BigNatural b3 = new BigNatural("346"); // one-argument String constructor
- BigNatural b4 = new BigNatural(b2); // one-argument BigNatural
- // constructor
- b1.increment();
- b3.decrement();
- System.out.println(b1.toString()); // should print out 1
- System.out.println(b4.toString()); // should print out 23
- }
- }
- public class BigNatural {
- private String num;
- public BigNatural(String input) {
- num = input;
- }
- public BigNatural(BigNatural input) {
- num = input.toString();
- }
- public BigNatural(Integer input) {
- num = input.toString();
- }
- public BigNatural() {
- Integer i = 0;
- num = i.toString();
- }
- public void increment() {
- Integer first = 0;
- Character ch = num.charAt(num.length()-1);
- Integer last = Character.digit(ch, 10);
- if (num.length() > 1)
- {
- if (last < 9) {
- last++;
- }
- else
- {
- if (num.length() >= 2)
- {
- last = 0;
- String temp = new String(num.substring(0, num.length()-2));
- increment();
- }
- else
- {
- last++;
- }
- }
- }
- else
- {
- if (last < 9)
- {
- last++;
- }
- else
- {
- last = 0;
- first = 1;
- }
- }
- String t = last.toString();
- if (first > 0)
- {
- String x = first.toString();
- num.concat(x);
- }
- num.concat(t);
- }
- public void decrement() {
- Character ch = num.charAt(num.length()-1);
- Integer last = Character.digit(ch, 10);
- if(num.length() > 1)
- {
- if(last == 0)
- {
- String temp = new String(num.substring(0, num.length()-2));
- decrement();
- }
- else
- {
- last--;
- }
- }
- else
- {
- if(last > 0)
- {
- last--;
- }
- else
- {
- last = 0;
- }
- }
- String t = last.toString();
- num.concat(t);
- }
- public String toString() {
- return num;
- }
- }
- public void increment() {
- num = increment(num);
- }
- private static String increment(String s) {
- if (s.length() <= 0) return "1";
- char ch = s.charAt(s.length() - 1);
- String top = s.substring(0, s.length() - 1);
- return ch < '9' ? top + ++ch : increment(top) + '0';
- }
- num.concat(t);
- public void increment() {
- add(1);
- }
- public void decrement() {
- add(-1);
- }
- private void add(int i) {
- // Your homework here ...
- // You will have only one function to debug and correct, not 2
- }