第七章第二十七题(相同的数组)(Same array)

第七章第二十七题(相同的数组)(Same array)

  • 7.27(相同的数组)如果两个数组list1和list2的内容相同,那么就说他们是相同的。使用下面方法头编写一个方法,如果list1和list2是相同的,该方法就返回true:
    public static boolean equals(int[] list1,int[] list2)
    编写一个测试程序,提示用户输入两个整数列表,然后显示他们两个是否相同。下面是运行示例。注意,输入的第一个数字列表中元素的个数。该数字不是列表的一部分。
    Enter list1:5 5 5 6 6 1
    Enter list2:5 2 5 6 1 6
    two lists are not identical
    Enter list1:5 2 5 6 6 1
    Enter list2:5 5 2 6 1 6
    Two lists are identical
    7.27(Same array)If the contents of two arrays LIST1 and List2 are the same, they are said to be the same. Write a method using the following method header. If LIST1 and List2 are the same, the method returns true:
    public static boolean equals(int[] list1,int[] list2)
    Write a test program, prompt the user to enter two integer lists, and then display whether they are the same. Here is a running example. Notice the number of elements in the first numeric list you enter. The number is not part of the list.
    Enter list1:5 5 5 6 6 1
    Enter list2:5 2 5 6 1 6
    two lists are not identical
    Enter list1:5 2 5 6 6 1
    Enter list2:5 5 2 6 1 6
    Two lists are identical

  • 参考代码:

    package chapter07;
    
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Code_27 {
        public static void main(String[] args) {
            Scanner input=new Scanner(System.in);
            System.out.print("Enter list1:");
            int length1=input.nextInt();
            int[] list1=new int[length1];
            for(int i=0;i<list1.length;i++){
                list1[i]=input.nextInt();
            }
    
            System.out.print("Enter list2:");
            int length2=input.nextInt();
            int[] list2=new int[length2];
            for(int i=0;i<list2.length;i++){
                list2[i]=input.nextInt();
            }
    
            if(equals(list1,list2)){
                System.out.println("Two lists are identical");
            }
            else System.out.println("TWo lists are not identical");
        }
        public static boolean equals(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;
        }
    }
    
    
  • 结果显示:

    Enter list1:5 2 5 6 6 1
    Enter list2:5 5 2 6 1 6
    Two lists are identical
    
    Process finished with exit code 0
    
    
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值