代码之家  ›  专栏  ›  技术社区  ›  Alamin

将数组中的每个数字乘以n-java

  •  0
  • Alamin  · 技术社区  · 10 年前

    有没有一种方法可以将数组中存储的每个数字乘以n。

    例如

    public static int [] intArray = new int [] {1,2,3,4,5,6,7};
    

    n=3

    它应该输出:3、6、9、12、15、18、21。

    我不知道如何做到这一点,我们将不胜感激!

    4 回复  |  直到 10 年前
        1
  •  4
  •   bcsb1001    10 年前

    Java 8方式,对于给定的n:

    Arrays.stream(intArray).map(i -> i * n).forEach(System.out::println);
    
        2
  •  3
  •   Du-Lacoste    10 年前

    这将是最简单的解决方案。

    public class Test{
        public static void main(String[] args) {
            int n=3;
            int [] intArray = new int [] {1,2,3,4,5,6,7};
           for(int i=0; i<intArray.length; i++) {
               System.out.println(intArray[i]*n);
           }
        }
    }
    
        3
  •  0
  •   Beaurocks16    10 年前

    如果你想让它超小,

    int n = 3;
    int[] intArray = blah;
    
    for (int i : intArray) {
        System.out.println(""+i*n); //The "" is to make the number i*n a string
    }
    
        4
  •  0
  •   Yosef Weiner    10 年前

    功能方法是使用Stream.map:

        int [] intArray = new int [] {1,2,3,4,5,6,7};
        int n = 3;
        System.out.println(Arrays.stream(intArray).map(i -> i * n).boxed().collect(Collectors.toList()));