Java 使用 for 循环打印数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36490166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:55:15  来源:igfitidea点击:

Printing array elements with a for loop

javaarrays

提问by Anne

This is a challenge question from my online textbook I can only get the numbers to prin forward... :(

这是我在线教科书中的一个挑战问题,我只能得到数字来打印...... :(

Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline. Ex: If courseGrades = {7, 9, 11, 10}, print: 7 9 11 10 10 11 9 7

编写一个 for 循环来打印 courseGrades 中的所有元素,每个元素后面都有一个空格(包括最后一个)。向前打印,然后向后打印。以换行符结束每个循环。例如:如果 courseGrades = {7, 9, 11, 10},则打印:7 9 11 10 10 11 9 7

Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.

提示:使用两个 for 循环。第二个循环从 i = NUM​​_VALS - 1 开始。

Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]).

注意:这些活动可能会使用不同的测试值来测试代码。此活动将执行两个测试,第一个使用 4 元素数组 (int courseGrades[4]),第二个使用 2 元素数组 (int courseGrades[2])。

import java.util.Scanner;

 public class CourseGradePrinter {
 public static void main (String [] args) {
  final int NUM_VALS = 4;
  int[] courseGrades = new int[NUM_VALS];
  int i = 0;

  courseGrades[0] = 7;
  courseGrades[1] = 9;
  courseGrades[2] = 11;
  courseGrades[3] = 10;

  /* Your solution goes here  */

  for(i=0; i<NUM_VALS; i++){
     System.out.print(courseGrades[i] + " ");
  }

  for(i=NUM_VALS -1; i>3; i++){
     System.out.print(courseGrades[i]+ " ");
     }

  return;
}
}

回答by Tim Biegeleisen

Your two loops almost were correct. Try using this code:

你的两个循环几乎是正确的。尝试使用此代码:

for (int i=0; i < NUM_VALS; i++) {
    // this if statement avoids printing a trailing space at the end.
    if (i > 0) {
        System.out.print(" ");
    }
    System.out.print(courseGrades[i]);
}

for (int i=NUM_VALS-1; i >= 0; i--) {
    if (i > 0) {
        System.out.print(" ");
    }
    System.out.print(courseGrades[i] + " ");
}

回答by Joels Elf

To print backwards you want:

要向后打印您想要的:

for(i = NUM_VALS - 1; i >= 0; i--) {
    System.out.print(courseGrades[i] + " ");
}
// To end with a newline
System.out.println("");

回答by A. Nony Mous

This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.

这是回答 zyBooks 问题的代码,6.2.3:用 for 循环打印数组元素。

 for (i = 0; i < NUM_VALS; i++) {
     System.out.print(courseGrades[i] + " ");
 }
 System.out.println("");

 for (i = NUM_VALS - 1; i >= 0; i--) {
    System.out.print(courseGrades[i] + " ");
 }

 System.out.println("");