자바에서 biginteger 클래스를 사용하지 않고 2 개의 큰 정수의 합을 계산해야하는 프로그램을 작성 중입니다. 내가 내 합계를 계산 루프에 붙어 있어요. 나는 여분의 0을 얻고 있습니다. 30 + 30 = 600입니다.2 개의 배열을 추가 할 때 여분의 0 자리가
잘못된 방법으로 배열을 반복하고 있기 때문에 꽤 확신합니다. 반대 방향으로 가야합니다 (숫자를 추가 할 때처럼 오른쪽에서 시작).하지만 배열 색인 오류가 발생하지 않으면 문제를 해결할 수 없습니다. 여기
내 코드입니다 :main:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
대형 정수 :
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
public LargeInteger(int[] array) {
intArray = array;
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
//get first array
public int[] getIntArray() {
return intArray;
}
//ADD method to add 2 arrays together
public LargeInteger add(LargeInteger secondInt){
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) +1 ];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++) {
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult/10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) ] = needToAdd;
return new LargeInteger(resultArray);
}
}
내가 변화하려 한 이런 일에 합의 루프 :
for(int i = maxIterations; i >= 0; i--)
투표의 여지가 남기십시오 : 검사를 통해 코드의 오류를 찾아내는 낯선 사람에게 질문하는 것은 생산성이 떨어집니다. 디버거 나 print 문을 사용하여 문제를 확인 (또는 적어도 격리) 한 다음보다 구체적인 질문으로 돌아 가야합니다 (10 줄 [테스트 케이스] (http : /sscce.org)). –
Java의 배열은 0을 기준으로합니다. 배열의 유효한 인덱스는 [0, array.length - 1]입니다. – Jeffrey
나는 정말로 오류를 발견하라고 요구하는 것으로 보지 못했다. 아마도 어쩌면 .. 나는 옳은 길을 가고 있는지, 그리고 내가 반대 방향으로 돌아갈 필요가 있는지 확실히 모르겠다. .. – Sackling