如何将数组A中的每个项目设置为初始值Java

huangapple go评论102阅读模式
英文:

How to set every item in the array A references to initialValue Java

问题

  1. public static void initialize(int A[], int initialValue) { ; }
  2. 这是我代码的开始我想知道怎样做可以使得运行后数组 A 中的每个项变为我设置的初始值这是一个学校作业教授告诉我们不能使用任何数组函数所以不能用 arrays.func
  3. 谢谢
英文:
  1. public static void initialize(int A[], int initialValue) { ; }

this is the start of my code, asking how you can make it so that after running, every item in the array A becomes what I made initialValue. It's for a school assignment and the professor told us we can't use anything with an arrays function so no arrays.func

Thanks!

答案1

得分: 5

你不需要那个方法。

只需调用:

  1. Arrays.fill(A, initialValue);

顺便提一下,你的标题有一个错误。你的数组是一个基本类型数组,因此它不会包含对 initialValue 的引用,而是会包含多次那个 int 值。

英文:

You don't need that method.

Just call

  1. Arrays.fill(A,initialValue);

BTW, your title has a mistake. Your array is a primitive array, so it won't contain references to initialValue, it will contain that int value multiple times.

答案2

得分: -1

这可以是另一种解决方案,

  1. /*
  2. * 初始化数组的一小部分,并使用System.arraycopy调用以二进制扩展的方式填充数组的其余部分
  3. */
  4. public static void initialize(int A[], int initialValue) {
  5. int len = A.length;
  6. if (len > 0){
  7. A[0] = initialValue;
  8. }
  9. for (int i = 1; i < len; i += i) {
  10. System.arraycopy(A, 0, A, i, ((len - i) < i) ? (len - i) : i);
  11. }
  12. }
  13. public static void main ( String [] args ) {
  14. int A[] = new int[5];
  15. initialize(A,1);
  16. for (int i : A) {
  17. System.out.println(A[i]);
  18. }
  19. }

输出:
1
1
1
1
1

英文:

This can be an another solution,

  1. /*
  2. * initialize a smaller piece of the array and use the System.arraycopy
  3. * call to fill in the rest of the array in an expanding binary fashion
  4. */
  5. public static void initialize(int A[], int initialValue) {
  6. int len = A.length;
  7. if (len &gt; 0){
  8. A[0] = initialValue;
  9. }
  10. for (int i = 1; i &lt; len; i += i) {
  11. System.arraycopy(A, 0, A, i, ((len - i) &lt; i) ? (len - i) : i);
  12. }
  13. }
  14. public static void main ( String [] args ) {
  15. int A[] = new int[5];
  16. initialize(A,1);
  17. for (int i : A) {
  18. System.out.println(A[i]);
  19. }
  20. }

OUTPUT:
1
1
1
1
1

huangapple
  • 本文由 发表于 2020年3月16日 22:25:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/60707743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定