Reading Integers into IntegerType array - java

I am supposed to write a program that reads integers from a txt file in an IntegerType array. I have created an IntegerType class that implements my AnyType interface as you will see in the code. I am then supposed to sort the array and study how many comparisons and swaps were made during the sorting to study the efficiency, which I know is O(N^2). I have set breakpoints in my code which showed me that the integers are being read into my String[] numbers array. When I try to add them to my IntegerType arrays, it hits the the while (scan.hasNext()) line of code and completely skips over my for loop to add the integers into my array. Anyone have any advice on how to resolve this? Thanks for your time. Here is my code:
My Sorting class:
public class Sorting {
public static void main(String[] args) throws IOException {
int type, sort;
Scanner read = new Scanner(System.in);
//Ask user for data type of input
System.out.println("Make selection by typing corresponding integer value and pressing Enter.");
System.out.println("Select type of input:");
System.out.println("1 = Integer 2 = String");
type = read.nextInt();
//Ask user for sorting algorithm desired
System.out.println("Select sorting algorithm to be used:");
System.out.println("1 = Insertion 2 = Selection 3 = Bubble");
sort = read.nextInt();
//Read in integer values from generated .txt files into corresponding integer arrays
Scanner scan = new Scanner(new File("descending.txt"));
String line = scan.nextLine();
String[] numbers = line.split(" ");
IntegerType[] worstCase = new IntegerType[numbers.length];
while (scan.hasNext()) {
for (int i = 0; i < worstCase.length; i++) {
worstCase[i] = new IntegerType(scan.nextInt());
}
}
scan = new Scanner(new File("random.txt"));
line = scan.nextLine();
numbers = line.split(" ");
IntegerType[] avgCase = new IntegerType[numbers.length];
while (scan.hasNext()) {
for (int i = 0; i < numbers.length; i++) {
avgCase[i] = new IntegerType(scan.nextInt());
}
}
scan = new Scanner(new File("ascending.txt"));
line = scan.nextLine();
numbers = line.split(" ");
IntegerType[] bestCase = new IntegerType[numbers.length];
while (scan.hasNext()) {
for (int i = 0; i < numbers.length; i++) {
bestCase[i] = new IntegerType(scan.nextInt());
}
}
if ((type == 1 || type == 2) && (sort == 1)) //Insertion Ascending
{
System.out.println("Insertion Sort / Ascending / Worst Case");
Sort.insertionSort(worstCase, worstCase.length);
System.out.println("Insertion Sort / Ascending / Average Case");
Sort.insertionSort(avgCase, avgCase.length);
System.out.println("Insertion Sort / Ascending / Best Case");
Sort.insertionSort(bestCase, bestCase.length);
}
}
}
My Sort class:
public class Sort {
public static void insertionSort(AnyType[] list, int size) {
int compare = 0, swap = 0;
AnyType key;
for (int i = 1; i < size; i++) {
key = list[i];
int j = i - 1;
compare++;
if ((j > -1) && (list[j].isBetterThan(key))) {
list[j + 1] = list[j];
j--;
swap++;
}
list[j + 1] = key;
}
System.out.println("There were " + compare + " comparisons made.");
System.out.println("There were " + swap + " swaps made.");
}
}
My AnyType Interface
public interface AnyType {
public boolean isBetterThan(AnyType datum);
}
My IntegerType class
public class IntegerType implements AnyType {
private int number;
IntegerType() {
number = 0;
}
IntegerType(int i) {
number = i;
}
IntegerType(String s) {
number = Integer.parseInt(s);
}
public boolean isBetterThan(AnyType datum) {
return (this.number > ((IntegerType) datum).number);
}
public int toInteger() {
return number;
}
}

I guess the file consists of space seperated integer values in one line.
Anyway you should use the Scanner.hasNextInt() methode, for checking.
So the problem is here (see comments):
//Read in integer values from generated .txt files into corresponding integer arrays
Scanner scan = new Scanner(new File("descending.txt"));
String line = scan.nextLine(); //reads already the whole line
String[] numbers = line.split(" "); //now a string array with all the values
//there is nothing left, everything is already stored in "line"/"numbers" variables
while (scan.hasNext()) {
//something
}
Since you do not now in advance how many integer values there will be, you need a dynamic data structure for your IntegerType values (f.e. an ArrayList). Or you iterate over the number array and convert every string value to an int:
Scanner scan = new Scanner(new File("descending.txt"));
String line = scan.nextLine();
String[] numbers = line.split("\\s+");
IntegerType[] worstCase = new IntegerType[numbers.length];
for(int i = 0; i < numbers.length; ++i)
worstCase[i] = new IntegerType(numbers[i]); //will work because IntegerType has a constructor which accepts a string
}
One more comment for your Sort methodes: They do not need the length of the array as parameter, you can just use array.length (but this is just flavor i guess).

Related

How can I check whether a value from one array exists in another array?

I have 3 arrays. One counts population, one sorts the population using arrays.sort and the other one stores strings. I want to essentially sort the strings from least to highest. Knowing that the value of where one population is stored is the same as where one string is stored i tried to match the sorted values to the population like this, it it seems to output the strings in the order that I wrote them. Where did I go wrong?
import java.util.Arrays;
public class test {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int Lvalue = 0;
int max = 0;
int min = 0;
int Svalue = 0;
System.out.println("How many countries will be entered");
int num = input.nextInt();
String[] country = new String[num];
int[] population = new int[num];
int[] popsort = new int[num];
String[] capital = new String[num];
for(int i = 0; i < num; i++)
{
System.out.println("Please enter the name of the country");
country[i] = input.next();
System.out.println("Please enter the country population");
population[i] = input.nextInt();
popsort[i] = population[i];
System.out.println("Please enter the country capital");
capital[i] = input.next();
}
for (int i = 0; i < num; i++)
{
if (population[i] > max)
{
max = population[i];
Lvalue = i;
}
}
for (int i = 0; i < num; i++)
{
if (population[i] < max)
{
min = population[i];
Svalue = i;
}
}
System.out.println("The country with largest pop is : " + country[Lvalue] + " ");
System.out.println("The country with smallest pop is : " + country[Svalue] + " ");
Arrays.sort(popsort);
for(int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
if (popsort[j] == population[i])
{
System.out.println(country[i]);
}
}
}
}
}
You can iterate through both arrays and do a comparison, you can use Arrays.binarySearch(), you can convert the array to a List with Arrays.asList() and use contains() on the list, etc. Also careful, you are doing something strange here: if (population[i] < max). That should compare with min, I think.
Instead of storing related information in separate variables, make a class and store information in the same object. Then write a comparator that can sort for you on the basis of the population count. This will also optimize your code.
Eg
class Country {
String name;
int population;
...more fields.
}
you can sort your array using comparator like:
List<Country> countries; // let say you stored all countries in a list or array
Arrays.sort(countries,(country1,country2)->{
return country1.getPopulation() - country2.getPopulation();
}

How to determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

How to sort String (more than 2 variables) alphabetically using compareTo() method?

I can't figure it out how to sort Strings (more than 2) using compareTo() method. For 2 I'm doing this:
Scanner input = new Scanner(System.in);
String name1 = input.nextLine();
String name2 = input.nextLine();
if(name1.compareTo(name2) < 0)
{
System.out.println(name1 + "\n" + name2);
}
else
{
System.out.println(name2 + "\n" + name1);
}
But what if I need sort more data from the users?
Thanks.
The following works without using arrays, lists or any other Collection, assuming you a priori know the number of Strings to be compared. This will compare 5 String values:
//use a max value for comparisons
private static final String MAX_STRING = String.valueOf(Character.MAX_VALUE);
public static void compareMe(String a, String b, String c, String d, String e) {
if (a.compareTo(b) <= 0) {
if (a.compareTo(c) <= 0) {
if (a.compareTo(d) <= 0) {
if (a.compareTo(e) <= 0) {
if (a != MAX_STRING) {
System.out.println(a);
a = MAX_STRING;
} else {
return;
}
}
//swap (a,e)
compareMe(e, b, c, d, a);
} else {
//swap (a,d)
compareMe(d, b, c, a, e);
}
} else {
//swap (a,c)
compareMe(c, b, a, d, e);
}
} else {
//swap (a,b)
compareMe(b, a, c, d, e);
}
}
Like Mick Mnemonic says, use Java's Collections classes and functionality. E.g.:
List<String> list = new ArrayList<>();
Scanner input = new Scanner(System.in);
//This should be a do-while list
list.add(input.nextLine());
list.add(input.nextLine());
Collections.sort(list);
for(String s: list) {
System.out.println(s);
}
This will sort the list ass follows: "Sorts the specified list into ascending order, according to the natural ordering of its elements." - http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
No compareTo required.
In java, if you want to sort many string items, you should put them into a container, usually is a string list(also can use array).
Talk is cheap, show you the code, this is an example of sort 5 strings.
Scanner input = new Scanner(System.in);
List<String> stringList = new ArrayList<String>();
for (int i = 0; i < 5; i++) { //exact number of string
stringList.add(input.nextLine());
}
System.out.println("before sort:" + stringList);
Collections.sort(stringList);
System.out.println("after sort:" + stringList);
update:
If you don't want to use Java collection framework's sort, if you really want to use compareTo() manually, you should implement a sort algorithm. Hear is an example that use bubble sort (But use compareTo() manually to sort is not the best practice).
Scanner input = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) { //exact number of string
list.add(input.nextLine());
}
System.out.println("before sort:" + list);
//bubble sort start
String temp;
int length = list.size();
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - 1 - i; j++)
if (list.get(j).compareTo(list.get(j + 1)) > 0) { //compareTo method
temp = list.get(j);
list.set(j, list.get(j + 1));
list.set(j + 1, temp);
}
}
//bubble sort end
System.out.println("after sort:" + list);
Here is an example piece of code which will allow you to add multiple strings to a list and then sort them using Java's default comparator.
import java.util.*;
public class Test
{
public static void main(String[] args)
{
boolean continueLoop = true;
List<String> myStringList = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("Please eneter a string");
myStringList.add(input.nextLine());
System.out.println();
System.out.println("Please eneter a second string");
myStringList.add(input.nextLine());
System.out.println();
while(continueLoop) {
System.out.println("Would you like to add another string");
System.out.println("Enter Yes to add another string");
System.out.println("Enter No to sort the strings");
System.out.println();
String yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("Yes")) {
System.out.println();
System.out.println("Please enter another string");
myStringList.add(input.nextLine());
System.out.println();
} else {
continueLoop = false;
System.out.println();
}
}
Collections.sort(myStringList);
System.out.println("Sorted Strings");
for(String s : myStringList) {
System.out.println(" " + s);
}
}
}
If your strings contain numbers and you want to sort them properly I would suggest taking a look at this comparator since it has been designed to do that. To implement this you would use this method; Collection.sort.
Collections.sort(myStringList, new AlphanumComparator());
Edit
For a specific number of strings you could use the following code
import java.util.*;
public class Test
{
public static void main(String[] args)
{
boolean continueLoop = true;
List<String> myStringList = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("Please eneter how many strings you will enter");
int j = Integer.parseInt(input.nextLine());
System.out.println();
for(int i=0;i<j;i++) {
System.out.println("Please eneter a string");
myStringList.add(input.nextLine());
System.out.println();
}
Collections.sort(myStringList);
System.out.println("Sorted Strings");
for(String s : myStringList) {
System.out.println(" " + s);
}
}
}
You are looking probably for this:
String[] arr = {"zsdsfc", "aazjkjf", "aabdd"};
System.out.println("Before:" + "\n");
for (int i = 0; i < arr.length; i++ ){
System.out.println(arr[i]);
}
System.out.println();
for (int i = 0; i < arr.length; i++ ){
for (int j = 0; j < arr.length; j++){
if(arr[i].compareTo(arr[j]) < 0){
String keeper = arr[i];
arr[i] = arr[j];
arr[j] = keeper;
}
}
}
System.out.println("After:" + "\n");
for (int i = 0; i < arr.length; i++ ){
System.out.println(arr[i]);
}
the A.CompareTo(B) method returns negative number if A is greater then B, zero if A is equal to B and positive number if B is greater then A.
You can have a look at the CompareTo(String) here.

extra 0 digit when trying to add 2 arrays

I am working on a program that needs to calculate the sum of 2 large integers without using the biginteger class in java. I am stuck on my for loop which calculates the sum. I am getting an extra 0 so 30 + 30 = 600.
I am pretty sure it is because I am looping through the arrays the wrong way. I need to go the opposite way (starting from the right side like you would when adding numbers) but I can't seem to fix it without getting an out of array index error.
here is my code:
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());
}
}
Large integer:
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 );
}
}
I have tried changing the for loop in sum to something like this:
for(int i = maxIterations; i >= 0; i--)
That for loop is only one of your problems.
1] you are not adding the carry properly.
2] a stack is more appropriate here than an array.
With a stack (place code inside your method):
Note: You are calling the function with number.add(num2);
public class LargeInt{
private String number;
public LargeInt(String num){
this.number = num;
}
public String add(String num2){
Stack<Integer> adder = toIntegerStack(this.number);//UPDATE
Stack<Integer> addend = toIntegerStack(num2);//UPDATE
Stack<Integer> result = new Stack<Integer>();
int carry =0;
int tmp = 0;
while(!.adder.isEmpty && !addend.isEmpty()){
tmp = adder.pop()+addend.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
while(!adder.isEmpty){
tmp = adder.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
while(!addend.isEmpty){
tmp = addend.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
//beyond this point the result is your answer
//here convert your stack to string before returning
}
}
UPDATE TO ANSWER COMMENT:
I am also editing above to call this function to fill stacks.
private Stack<Integer> toIntegerStack(String n){
Stack<Integer> stack = new Stack<Integer>();
for(char c: n.toCharArray())
stack.push(c-48);//ASCII
return stack;
}//toStack(String)
If you insist on using array, you must follow the same pattern with your array.
int indexA=0;
int indexB=0;
int[] result = new int[1+A.length>B.length?A.length:B.length];
int indexResult=result.length-1;
while(indexA < A.length && indexB <B.length){//inside is same idea
tmp = A[indexA++] + B[indexB++] + carry;
//... do here as for stacks for tmp and carry
result[indexResult--];
}
while(indexA < A.length){
//do as in stack version
}
while(indexB < B.length){
//do as in stack version
}
Your adding code assumes that the least significant digit is in array[0], but your reading code puts the most significant digit there. You should reverse the array after reading.

Wrong return type in method

I need to make a program that adds long integers without using the biginteger class.
I am working on the add method now and I think I have it correct but I am stuck on returning the correct data type for my method and I'm not sure how to correct it.
Here are my 2 classes so far:
Main Class:
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());
}
}
LargeInteger.class:
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
}
//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;
}
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) + 1] = needToAdd;
return resultArray;
}
}
You need a second LargeInteger constructor:
public LargeInteger( int[] array ) {
intArray = array
}
Then your method can return:
return new LargeInteger( resultArray );
Well first thing, your method add in LargeInteger is supposed to return a LargeInteger, but instead returns an array (int[]). You could fix this by adding a constructor for LargeInteger that takes in an int[] parameter (i.e. LargeInteger(int[] digitArray)). Then, in your add method you could simply do: return new LargeInteger(resultArray);.

Categories