In: Computer Science
(java) Part 1 Write a method named compare that accepts two String arrays as parameters and returns a boolean. The method should return true if both arrays contain the same values (case sensitive), otherwise returns false. Note - the two arrays must be the same length and the values must be in the same order to return true.
Part 2 Write a method named generateArray that accepts an int size as its parameter and returns an int[] array where each element is populated incrementally beginning at 1 and ending at the size (inclusive). Example: if the parameter was 5, your method should return an int[] array containing values: {1,2,3,4,5}. Example 2: if the parameter was 9 your method should return an int[] array containing values: {1,2,3,4,5,6,7,8,9}. Hint - try to populate the array with 0 - size-1 first and then adjust :) *You may assume they will enter a positive number.
Main.java exists to test your code - write the methods described below in Assignment10.
public class Main
{
public static void main(String[] args) {
//You can test your code here.
//Sample testing code:
Assignment10 q = new Assignment10(); //creates an object of your
class
/* //TEST PROBLEM 1 - Uncomment to use
String[] a = {"dog", "cat"};
String[] b = {"dog", "cat", "banana"};
System.out.println(q.compare(a,b)); //should print false - a &
b do not contain same elements and are not the same length
*/
//Change values around to ensure your code works properly
/* //TEST PROBLEM 2 - Uncomment to use
//Continues using object q created in line 9. ***Testing code
requires your additions.
int size = 3; //change number to thoroughly test.
int[] returnedArray = q.generateArray(size); //returns an array -
stored in an array.
//TODO: write a simple for loop to print out each element of the
array to test
//YOUR CODE HERE TO FINISH TESTING (TODO instructions
above!).
//Note: System.out.println(returnedArray); should not be used -
prints a memory address - why?
*/
}
}
Code
import java.util.*;
class Assignment10
{
public boolean compare(String a[],String b[])
{
if(a.length!=b.length) //if different length return false
{
return false;
}
for(int i=0;i<a.length;i++)
{
if(!a[i].equals(b[i])) //if any element mismatched return false
return false;
}
return true; //return true if all equals
}
public int[] generateArray(int n)
{
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=i+1; //store in the array
}
return a;
}
}
public class Main
{
public static void main(String args[])
{
Assignment10 q = new Assignment10();
String[] a = {"dog", "cat"};
String[] b = {"dog", "cat", "banana"};
System.out.println(q.compare(a,b));
int size = 3;
int[] returnedArray = q.generateArray(size);
for(int i=0;i<size;i++)
{
System.out.print(returnedArray[i]+" ");
}
}
}
Terminal Work
.