JAVA PROGRAM-- The arrays list1 and list2 are identical, if they contain the sam
ID: 3686590 • Letter: J
Question
JAVA PROGRAM--
The arrays list1 and list2 are identical, if they contain the same elements (possibly in different order). Write a method that returns true if list1 and list2 are identical, using the following header:
public static boolean sameValues (int[] list1, int[] list2)
Write a test program that prompts user to enter two lists of integers and displays whether the two are strictly identical. Here are the sample runs. Note that the first number in the input indicated the number of elements in the list; it is not part of the list.
Hint: use Arrays.copyOf and Arrays.sort methods.
Create a wrapping do-while loop allowing user to repeat the process upon request.
OUTPUT:
Enter list1, starting with the number of elements: 523546
Enter list2, starting with the number of elements: 525346
Two lists are the same
Enter list1, starting with the number of elements: 523364
Enter list2, starting with the number of elements: 522364
Two lists are not the same
Explanation / Answer
import java.util.Arrays;
import java.util.Scanner;
public class IdenticalList {
public static boolean sameValues(int[] list1, int[] list2) {
if (list1.length != list2.length)
return false;
Arrays.sort(list1);
Arrays.sort(list2);
for (int i = 0; i < list1.length; i++) {
if (list1[i] != list2[i])
return false;
}
return true;
}
public static void main(String[] args) {
char choice = 'y';
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter list1: ");
String l1 = sc.next();
System.out.print("Enter list2: ");
String l2 = sc.next();
// creating two list
int list1[] = new int[l1.charAt(0) - '0'];
int list2[] = new int[l2.charAt(0) - '0'];
// filling list1 and list 2 from user input
for (int i = 1; i < l1.length()-1; i++)
list1[i] = l1.charAt(i) - '0';
for (int i = 1; i < l2.length()-1; i++)
list2[i] = l2.charAt(i) - '0';
if (sameValues(list1, list2))
System.out.println("Two list are the same");
else
System.out.println("Two list are not same");
System.out.print("Do you want to test more list ? (n to stop): ");
choice = sc.next().charAt(0);
} while (choice != 'n');
}
}
/*
Output:
Enter list1: 523546
Enter list2: 525346
Two list are the same
Do you want to test more list ? (n to stop): y
Enter list1: 523364
Enter list2: 522364
Two list are not same
Do you want to test more list ? (n to stop): n
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.