如何使用Array储存两组数,并且确定这两组数相同?
使用Array储存数组1和数组2,并且使用类函数public static boolean equal(int[] list1, int[] list2)去确定两组数是否相同。
示例如下
Enter list1:
5 2 5 6 6 1
Enter list2:
5 5 2 6 1 6
The two lists are identical.
Enter list 1:
5 5 5 6 6 1
Enter list 2
5 2 5 6 1 6
The two lists are not identical
我写的代码如下无法运行
import java.util.Scanner;public class identical{ public static void main(String[] args){ Scanner input=new Scanner(System.in); boolean[] equal=new boolean[]; System.out.println("Enter list1:"); int[] list1=new int[6]; for (int i=0;i<list1.length;i++){ list1[i]=input.nextInt(); } System.out.print("Enter list2:"); int[] list2=new int[6]; for (int i=0;i<list2.length;i++){ list2[i]=input.nextInt(); } equal(list1[i],list2[i]); } public static boolean equal(int[] list1,int[] list2){ boolean allEqual=true; for (int 1=0,i<equal.length,i++){ list1[i]=list2[i]; if (equal){ allEqual=true; System.out.println("The two lists are identical."); return allEqual; } else { System.out.println("The two lists are not identical."); break; } } }}
import java.util.Arrays;import java.util.Scanner;public class identical { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter list1:"); int[] list1 = new int[6]; for (int i = 0; i < list1.length; i++) { list1[i] = input.nextInt(); } System.out.println("Enter list2:"); int[] list2 = new int[6]; for (int i = 0; i < list2.length; i++) { list2[i] = input.nextInt(); } Arrays.sort(list1); Arrays.sort(list2); equal(list1, list2); } public static void equal(int[] list1, int[] list2) { for (int i = 0; i < list1.length; i++) { if (list1[i] != list2[i]) { System.out.println("The two lists are not identical."); return; } } System.out.println("The two lists are identical."); }}
[解决办法]
第二道题,好好学学基础吧,顺便结个贴。。。
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Scanner;import java.util.TreeMap;public class occurrences { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the integers between 1 and 100:"); List<Integer> data = new ArrayList<Integer>(); int num = input.nextInt(); while (num != 0) { data.add(num); num = input.nextInt(); } Map<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int key : data) { if (map.containsKey(key)) { map.put(key, map.get(key) + 1); } else { map.put(key, 1); } } for (int key : map.keySet()) { System.out.println( key + " no of occurrences: " + map.get(key)); } }}