user2990394
user2990394

Reputation: 55

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!

Upvotes: 0

Views: 171

Answers (1)

bcorso
bcorso

Reputation: 47058

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.

    If, instead, you wanted to loop only while a certain condition holds you would use a while loop: (e.g. while(condition) loop;).

  2. System.out.println() will print a new line after each call, and \t will add a tab.

For better formatting check out this Oracle doc on using printf and format

Upvotes: 2

Related Questions