从扫描器到数组Java读取整数

时间:2017-11-14 07:49:13

标签: java arrays class count

我有一个简单的练习问题,我需要创建一个方法 readArray 应阅读(使用扫描仪) ñ 整数并返回一个长度数组 ñ 按照读取的顺序存储整数。在读取整数之前,应该打印方法 ñ 表示预期有多少整数。应该通过调用读取数组生成xyz的方式创建方法main

我收到编译错误" ReadCompareArrays类型中的方法readArray(int)不适用于arguments()"我该如何更正代码?

import java.util.Scanner; 
public class ReadCompareArrays {
    public static int[] readArray(int n)
    {
        System.out.println("Insert 3 integers");
        Scanner s = new Scanner(System.in);
        int count = s.nextInt();
        int[] array = new int[count];
        return array;
    }
    public static boolean equalArrays (int [] a, int [] b) 
    {
        boolean result = true;  
        for(int i = 0; i < b.length; i++)
            {
                if (a[i] == b[i++] && a.length == b.length) { 
                    result = true;
                }
                else {result = false;}
            }
        return result;
    }   
    public static void main (String[] args)
    {
        int[] x = readArray();
        int[] y = readArray();
        int[] z = readArray();
        System.out.print(equalArrays(x,y));
        System.out.print(equalArrays(y,z));
    }
}

1 个答案:

答案 0 :(得分:1)

您的readArray方法错误。它只是实例化数组,你设置了多少元素,然后只返回它,你还需要在返回数组之前读取元素。此外,equalArrays可以更简单。  代码看起来应该是这样的:

import java.util.Scanner; 
import java.util.Arrays;
    public class ReadCompareArrays {
    public static int[] readArray()
    {
        Scanner s = new Scanner(System.in);
        System.out.println("hoW many integeres do you want in the array?");
        int count = s.nextInt();
        System.out.println("count is: " + count);
        int[] array = new int[count];
        for(int i = 0; i < count; i++)
        array[i] = s.nextInt();
        return array;
    }
        public static boolean equalArrays (int [] a, int [] b) 
        {
            if(Arrays.equals(a,b))
               return true;
            return false;
        }   
        public static void main (String[] args)
        {
            int[] x = readArray();
            int[] y = readArray();
            int[] z = readArray();
            System.out.print(equalArrays(x,y));
            System.out.print(equalArrays(y,z));
        }
    }