public class NaturalNumber
{
int[] data = {};
private int toInt(char c)
{
return (int)c - (int)'0';////converses a digit character to its integer value
}
我想将initData
中的数字存储为数组数据中的整数。我尝试了这个但是没有用。
public NaturalNumber(String initData)
{
int[]data =new int[10];
for(int i=0;i<10;i++)
data[i] =Character.digit(initData.charAt(i), 10);}
/**compare this to other number and find out which one bigger or are they equal*/
public int compareTo(NaturalNumber other)
{
}
/**I want to set digitIndex between 0 and data.length - 1 and value to between 0 and 9*/
public void setDigit(int digitIndex, int value)
{
digitIndex=Math.max(0,data.length-1);
value=Math.max(0,9);
}
答案 0 :(得分:0)
NaturalNumber(String initData)
构造函数存在索引超出范围的问题,例如:
public static class NaturalNumber {
private int[] data;
public NaturalNumber(String initData) {
final int length = initData.length();
data = new int[length]; // now we should have enough space
for(int i = 0; i < length; i++) {
// Also there won't be any mismatch in size between
// initData and the maximum value for i so you don't
// risk getting a IndexOutOfBoundsException
data[i] = toInt(initData.charAt(i));
}
}
private static int toInt(char c)
{
return (int)c - (int)'0'; // converts a digit character to its integer value
}
// possible implementation of compareTo
public int compareTo(NaturalNumber that) {
final int length = this.data.length;
if(length != that.data.length) {
return Integer.compare(length, that.data.length);
}
for(int i = 0; i < length; i++) {
if(this.data[i] != that.data[i]) {
return Integer.compare(this.data[i], that.data[i]);
}
}
return 0;
}
public void setDigit(int index, int value) {
if(value < 0 || value > 9) {
return;
}
if(index < 0 || index > data.length - 1) {
return;
}
data[index] = value;
}
}