(Identical arrays) The arrays list1 and list2 are identical if they have the sam
ID: 3765111 • Letter: #
Question
(Identical arrays) The arrays list1 and list2 are identical if they have the same contents. Write a method that returns true if list1 and list2 are identical, using the following header: public static boolean equals(int[] list1, int[] list2)
Write a test program that prompts the user to enter two lists of integers and displays whether the two are identical.
Design the main method of your program such that it allows the user to re-run the program with different sets of inputs. Document your code, and organize and space the outputs properly. Use escape characters and formatting objects when applicable.
Explanation / Answer
Two arrays list1 and list2 are defined as integer arrays of size 5, so enter only 5 elements for each array or change the array size as per the need. Also invalid input is not cheked or filtered.
Here is the code
import java.util.*;
import java.io.*;
public class equalArrays{
public static void promptUser()
{
}
public static boolean equals(int[] list1, int[] list2)
{
for(int i=0;i<5;i++)
{
if(list1[i]!=list2[i]) // actual comparison of two arrays
{
return false;
}
}
return true;
}
public static void main(String[] args) {
int [] list1=new int[5]; // list1 of size 5
int [] list2=new int[5]; // list2 of size 5
System.out.printf(" Program started. Press 'ctrl c' to exit from the program ");
Scanner scanner = new Scanner(System.in);
while(true) // infinite loop to re run the program or press ctrl +c to exit
{
System.out.printf(" Enter List1: ");
for(int i=0;i<5;i++)
{
list1[i]=scanner.nextInt(); //read list 1 elements
}
System.out.printf(" Enter List2: ");
for(int i=0;i<5;i++)
{
list2[i]=scanner.nextInt(); // read list 2 elements
}
if(equals(list1,list2)) // call equals function to compare the two lists
System.out.println(" Lists are equal");
else
System.out.println(" Lists are not equal");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.