如何在不影响其他元素的情况下修改某些数组元素?

时间:2018-04-29 13:41:13

标签: java arrays

我正在尝试创建一个Java程序,我将数组的元素更改为2,将其更改为4,将等于4的元素更改为8,将等于8的元素更改为2.我无法弄清楚如何以这样的方式改变这些元素,即我不改变那些已经被切换的元素,因此我最终得到了一堆2个。

import java.io.IOException;
import java.util.Scanner;

public class Prob8Array {
    static int n, i;

    public static void main(String[] args) throws IOException {
        Scanner reader = new Scanner(System.in);
        System.out.println("Nr of array elements:");
        n = reader.nextInt();

        System.out.println("Array elements:");
        int[] a = new int[n];

        for(i = 0;i < n; i++) {
            a[i] = reader.nextInt();
        }

        reader.close();
        for (i=0; i < n; i++) {
                if (a[i] == 2) {
                    a[i] = 4;
                }
                if (a[i]==4) {
                    a[i] = 8;
                }
                if (a[i]==8) {
                    a[i]=2;
                }
        } 
        for (i=0; i<n; i++)
            System.out.println(a[i]);
    }
}

这是我能想到的最好的,但它显然不会像我想要的那样工作。

4 个答案:

答案 0 :(得分:1)

由于您使用的是if语句,因此您可以为单个数组元素执行多个语句。将它们更改为if..else if..else结构。

if (a[i] == 2) {
    a[i] = 4;
} else if (a[i] == 4) {
    a[i] = 8;
} else (a[i] == 8) {
    a[i] = 2;
}

答案 1 :(得分:0)

您希望每个数组元素最多进行一次更改,这意味着如果任何条件为true,则您不希望评估以下条件。这可以通过if-else-if:

来实现
for (i = 0; i < n; i++) {
    if (a[i] == 2) {
        a[i] = 4;
    } else if (a[i] == 4) {
        a[i] = 8;
    } else if (a[i] == 8) {
        a[i] = 2;
    }
} 

另一种选择是使用switch声明:

for (i = 0; i < n; i++) {
    switch (a[i]) {
    case 2:
        a[i] = 4;
        break;
    case 4:
        a[i] = 8;
        break;
    case 8:
        a[i] = 2;
        break;
    }
} 

答案 2 :(得分:0)

你必须使用if,否则如果要避免输入每个if ::

       if (a[i] == 2) {
            a[i] = 4;
        }
        else if (a[i]==4) {
            a[i] = 8;
        }
        else if (a[i]==8) {
            a[i]=2;

      }

答案 3 :(得分:0)

您真的不需要第二个for-loop,您可以使用三元运营商这样动态执行此操作:

import java.io.IOException;
import java.util.Scanner;

public class Prob8Array {
    static int n, i;

    public static void main(String[] args) throws IOException {
        Scanner reader = new Scanner(System.in);
        System.out.println("Nr of array elements:");
        n = reader.nextInt();

        System.out.println("Array elements:");
        int[] a = new int[n];

        for(i = 0;i < n; i++) {
            int value = reader.nextInt();
            a[i] = (value==2)? 4 : (value==4)? 8 : (value==8)? 2 : value;
        }

        reader.close();

        for (i=0; i<n; i++) System.out.println(a[i]);
    }
}

<强>测试

enter image description here

相关问题