如何在同一行上使用for循环输出存储在数组中的多个值?

我创建了数组,当我输入数组的值时,它们分别显示在单独的行上……

输入第一个数组的值:75
48
23

我希望数字显示在同一行上,但不确定如何执行。谢谢您的帮助。

public class CompareArrays
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int arraySize;

        System.out.print("Enter the array size: ");
        arraySize = input.nextInt();

        int[] array1 = new int[arraySize];
        int[] array2 = new int[arraySize];

        System.out.print("Enter the values for the first array: ");
        for(int i = 0; i < arraySize; i++) {
            array1[i] = input.nextInt();
        }

        System.out.print("Enter the values for the second array: ");
        for(int i = 0; i < arraySize; i++) {
            array2[i] = input.nextInt();
        }

        if(Compare(array1,array2)) {
            System.out.println("Judgement: \t The arrays are identical");
        }else {
            System.out.println("Judgement: \t The arrays are not identical");
        }
        input.close();
    }

    public static boolean Compare(int[] array1,int[] array2)
    {   
        for (int i = 0; i < array1.length; i++) {
            if(array1[i] != array2[i]) {
                return false;
            }
        }
        return true;
    }
}
caoxc328 回答:如何在同一行上使用for循环输出存储在数组中的多个值?

在控制台中输入这些值时,您要按Enter键,这就是为什么它看起来在不同的行上的原因。如果要在1行上输入值,则可以将其作为字符串输入并分割。

如果您只想在一行上打印数组,则可以使用基本的for循环并使用System.out.print()来完成。

int[] a = {1,2,3,4};

for(int i = 0; i < a.length; i++) {
    System.out.print(a[i] + " ");
}
本文链接:https://www.f2er.com/3134052.html

大家都在问