Comp Sci Java Class Arrays: ArrayTest Method

AI Thread Summary
The discussion focuses on creating a Java class named ArrayTest with a method called arrayCombiner, which initializes three arrays of size 10. The first array contains odd numbers, the second contains even numbers, and the third array sums the corresponding elements from the first two. A loop is used to populate the odd and even arrays, while another loop prints the contents of the sum array. The provided code demonstrates a successful implementation of this logic, ensuring the correct population and output of the arrays. The solution effectively meets the homework requirements.
glebovg
Messages
156
Reaction score
0
Homework Statement

Create a Java class named ArrayTest with a method called arrayCombiner that creates three arrays of size 10. The first array should contain the values 1, 3, 5, 7, 9, 11, 13, 15, 17, and 19. The second array should contain the values 2, 4, 6, 8, 10, 12, 14, 16, 18, and 20. Using loops, populate the third array with the sum of the value of the number at the same index location from the other two arrays. For example, the first element will be 3 (1+2), the second will be 7 (3 + 4) etc. Write another loop that loops through the third array and prints out its contents.

The attempt at a solution

Code:
public class ArrayTest
{
public static void main(String[] args)
{
arrayCombiner();
} // end main
public static void arrayCombiner()
{
int[] odd=new int[10];
int[] even=new int[10];
int[] sum=new int[10];
int count=0;
int i=1;
while(count<10)
{
odd[count]=i;
even[count]=i+1;
sum[count]=i+(i+1);
count++;
for(int sumCount:sum)
{
System.out.printf("%d ",sumCount);
}
 }
  } // end arrayCombiner
   } // end class ArrayTest
 
Physics news on Phys.org


I got it.

Code:
public class ArrayTest
{
	public static void main(String[] args)
	{
		arrayCombiner();
	} // end main
	public static void arrayCombiner()
{
	int[] odd=new int[10]; // create strings of length 10
	int[] even=new int[10];
	int[] sum=new int[10];
	int counter=0; // initialize counter
	int i=1; // initialize variable
	while(counter<10)
{
	odd[counter]=i; // assign new content to strings
	even[counter]=i+1;
	sum[counter]=odd[counter]+even[counter];
	counter++;
	i+=2;
}
	for(int total:sum)
	{
	System.out.printf("%d ",total);
	}
} // end arrayCombiner

} // end class ArrayTest
 

Similar threads

Replies
2
Views
1K
Replies
1
Views
2K
Replies
5
Views
2K
Replies
7
Views
2K
Replies
5
Views
3K
Replies
12
Views
2K
Replies
1
Views
2K
Back
Top