简体   繁体   English

使用循环打印数组的输出?

[英]Using a loop to print output of arrays?

import java.io.*; 
import java.util.*;

public class AP_ExamArray
{

//User Input AP Exam Scores Using For Loops
public static void main(String args[])
{

   int [] scores = new int[5];

   int j;
   int sum_exam=0;

   for (j=0; j<scores.length; j++)
   {
   Scanner kbReader = new Scanner(System.in);
   System.out.println("Please enter AP Exam Score (1-5): ");
   scores[j]=kbReader.nextInt();
   sum_exam+=scores[j];
   }

//Initializer List Final Percentage

double [] final_percent = {97.3, 89.8, 96.2, 70.1, 93.0};

double sum_percent=0;
int k;

for(k=0; k<final_percent.length;k++)
{
sum_percent+=final_percent[k];
}

// String array containing last name (while loop)
String [] last_name = new String[5];
int i=0;
   while (i<last_name.length)
   {
   Scanner kbReader = new Scanner(System.in);
   System.out.println("Please enter last name: ");
   last_name[i]=kbReader.next();
   i++;
   }

//Average Exam Scores

double avg_exam = (double) sum_exam/scores.length;

//Average Final Percentage

double avg_percent = (double) sum_percent/final_percent.length;


}
}

The directions are: 方向是:

"For your output use a loop to print the student names, percentages, and test score, and be sure to include appropriate data below each column heading: “对于您的输出,使用循环打印学生姓名,百分比和测试分数,并确保在每个列标题下方包含适当的数据:

Student Name Student Percentage Student Test Score." 学生姓名学生百分比学生考试成绩。“

I'm not sure how to do this! 我不知道怎么做!

How about: 怎么样:

for(i=0; i<scores.length; i++)
    System.out.println(last_names[i] +"\t"+ final_percent[i] +"\t"+ scores[i]);
  1. A for loop is used because you want to loop through the entire array of a known size. 使用for循环是因为您想循环遍历已知大小的整个数组。

    If, instead, you wanted to loop only while a certain condition holds you would use a while loop: (eg while(condition) loop; ). 相反,如果您只想在某个条件成立while循环,则使用while循环:(例如while(condition) loop; )。

  2. System.out.println() will print a new line after each call, and \\t will add a tab. System.out.println()将在每次调用后打印一个新行,并且\\t将添加一个选项卡。

For better formatting check out this Oracle doc on using printf and format 为了更好的格式化检查出这个甲骨文的文档使用printfformat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM