开发者

Trouble with constructor: Natural Number using Stack<Integer>

I'm trying to create an arbitrarily long natural number using a stack of integers. I'm pretty new to Java, but here's what I've got so far:

import java.util.Stack;

public class BigNatural {      // I didn't choose that name >.>

private Stack< Integer > number;

public BigNatural(String value_in) {

while(value_in.length() > 0) {

char temp_char = value_in.charAt(0);

Integer temp_int = Character.digit(temp_char, 10);

this.number.push(temp_int);

if(value_in.length() > 1) {
value_in = value_in.substring(1); }

else { break; }
}
}

I'm getting a NullPointerException on the line with this.number.push. Is there something I'm not doing in terms of initializing the Stack correctly? Adding number = new Stack< Integer >(); allowed my initialize test to run, but I feel like that on开发者_开发知识库ly creates a local Stack that goes out of scope. Help!

Edit: (see comments below)

public void increment () {
  Integer temp_int = 0;

  if(!this.number.empty()) {

    temp_int = this.number.pop();
    temp_int++;

    if(temp_int == 10) {
      this.increment();
      this.number.push(0);
    } else { 
      this.number.push(temp_int); 
    }    
  } else { 
    this.number.push(1);
  }
}

Thanks again in advance for any help!


Adding number = new Stack< Integer >(); allowed my initialize test to run, but I feel like that only creates a local Stack that goes out of scope.

It won't be going "out of scope", because you're saving it in the class member number.


It will not go out of scope because you assign the newly created Stack to the class variable number.

Furthermore, the NullPointerException is thrown because number is not initialized.

You need to initialize number before the while loop, or you can change this line:

private Stack<Integer> number;

to

private Stack<Integer> number = new Stack<Integer>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜