Reputation: 147
I have to read a text file and make the first number of each line a size of an array. Then I had to populate a 3rd array with the first two arrays. No matter what I try I always get the contents of the first array into the 3rd array, but I get an out of bounds exception going to the 2nd. What am I doing wrong?
import java.util.*;
import java.io.*;
public class sort
{
public static void main (String[] args)
{
File file = new File("twoLists.txt");
try
{
Scanner read = new Scanner(file);
int size = read.nextInt();
//array 1 size and population
int list1[] = new int[size];
for (int i = 0; i < list1.length; i++)
{
list1[i] = read.nextInt();
}
//array2 size and population
int size2 = read.nextInt();
int list2[] = new int[size2];
for (int i = 0; i < list2.length; i++)
{
list2[i] = read.nextInt();
}
//combine the arrays
int list3[] = new int[list1.length + list2.length];
for (int i = 0; i < list3.length; i++)
{
//if i is < the length of list 1 populate the array
//with contents of list
if (i < list1.length)
{
list3[i] = list1[i];
}
if (i > list1.length)
{
list3[i] = list2[i];
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 60
Reputation: 2673
use this code instead :
int j=0;
for (int i = 0; i < list3.length; i++)
{
//if i is < the length of list 1 populate the array
//with contents of list
if (i < list1.length)
{
list3[i] = list1[i];
}
if (i > list1.length)
{
list3[i] = list2[j++];
}
}
you're using the same index for list3 and list2 which are very different in size(list3 is list2 and list1 combined), if you don't like defining a new variable try this:
for (int i = 0; i < list3.length; i++)
{
//if i is < the length of list 1 populate the array
//with contents of list
if (i < list1.length)
{
list3[i] = list1[i];
}
if (i > list1.length)
{
list3[i] = list2[i-list1.length];
}
}
you can also seperate it into two for loops and defining i outside the loop,after all the compiler will loop over list3 whether one loop or two loops.
Upvotes: 1
Reputation: 8390
Your mistake is here:
if (i > list1.length)
{
list3[i] = list2[i];
}
You say that i
must be greater than list1.length
, but require the value of i
- change it to this to make it work:
if (i > list1.length)
{
list3[i] = list2[i-list1.length];
}
Upvotes: 3
Reputation: 20520
Your problem is here:
if (i > list1.length)
{
list3[i] = list2[i];
}
You're correctly indexing list3
, but you're acting as if the indexing of list2
carried on from where list1
left off. It doesn't: it starts from 0, just like all arrays.
Try
if (i > list1.length)
{
list3[i] = list2[i-list1.length];
}
and that should sort things out.
Upvotes: 2