JOptionPane inputs to array for mean - java

I am trying to make a grade book that takes the inputs of five assignments for X amount of students and comes up with a final grade for each student. The program successfully loops according to the number of students entered, and compiles correctly. However, I need to come up with the averages of each assignment based on the whole class. I'm trying to accomplish this with arrays, but I'm desperately stuck.
int numStudents = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter number of students: "));
String[] examOneGrade = new String[numStudents];
String[] examTwoGrade = new String[numStudents];
String[] examFinalGrade = new String[numStudents];
String[] projectGrade = new String[numStudents];
String[] homeworkGrade = new String[numStudents];
// loops depending on number of students in the class
for (int i = 0; i < numStudents; i++) {
String name = JOptionPane.showInputDialog(null, "Enter Student Name: ");
JOptionPane.showMessageDialog(null, "Enter Grades for " + name,
" ", JOptionPane.PLAIN_MESSAGE);
examOneGrade[i] = JOptionPane.showInputDialog(null, "Enter Exam 1 Grade: ");
examTwoGrade[i] = JOptionPane.showInputDialog(null, "Enter Exam 2 Grade: ");
examFinalGrade[i] = JOptionPane.showInputDialog(null, "Enter Final Exam Grade: ");
projectGrade[i] = JOptionPane.showInputDialog(null, "Enter Project Grade: ");
homeworkGrade[i] = JOptionPane.showInputDialog(null, "Enter Homework Grade: ");
// converts strings to floats
float exam1 = Float.parseFloat(examOneGrade[i]);
float exam2 = Float.parseFloat(examTwoGrade[i]);
float finalExam = Float.parseFloat(examFinalGrade[i]);
float project = Float.parseFloat(projectGrade[i]);
float homework = Float.parseFloat(homeworkGrade[i]);
// weights
float number1 = exam1 * .10f;
float number2 = exam2 * .10f;
float number3 = finalExam * .30f;
float number4 = project * .30f;
float number5 = homework * .20f;
// calculates student final grade
float grade = number1 + number2 + number3 + number4 + number5;
JOptionPane.showMessageDialog(null, "Final Grade: " + grade,
" " + name, JOptionPane.PLAIN_MESSAGE);
}
I'm not asking to be given the answer, I'm just desperate to know if I'm on the right path and where I should be looking. This exact topic seems to be nonexistent.
My attempt at a low grade method:
public int getMinimum(List<Student> studentList) {
float lowGrade = getExamOneGrade[0];
for(Student student : studentList) {
if(student.getExamOneGrade() < lowGrade) {
lowGrade = getExamOneGrade;
}
}
return lowGrade;
}

Well, basically there's nothing wrong about your approach. But you should go one step further and put all the information and computations concerning a single student in an object. E.g.
Please note, that this is just a brief example. You have to complete it on your own.
public class Student {
private String name;
private float examOneGrade;
private float examTwoGrade;
private float examFinalGrade;
private float projectGrade;
private float homeworkGrade;
// getters and setters
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public float getExamOneGrade(){
return examOneGrade;
}
public void setExamOneGrade(float examOneGrade) {
this.examOneGrade = examOneGrade;
}
// and so on ...
// weight computation goes here
public float getExamOneWeight() {
return examOneGrade * .10f;
}
public float getExamTwoWeight() {
return examOneGrade * .10f;
}
// ...
public float getFinalGrade {
return getExamOneWeight() +
getExamTwoWeight() +
// ...
getHomeworkWeight();
}
}
Then in your code
int numStudents = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter number of students: "));
List<Student> studentList = new ArrayList<Student>();
// loops depending on number of students in the class
for (int i = 0; i < numStudents; i++) {
Student student = new Student();
student.setName(JOptionPane.showInputDialog(null, "Enter Student Name: "));
JOptionPane.showMessageDialog(null, "Enter Grades for " + student.getName(),
" ", JOptionPane.PLAIN_MESSAGE);
student.setExamOneGrade(Float.parseFloat(JOptionPane.showInputDialog(null, "Enter Exam 1 Grade: ")));
student.setExamTwoGrade(Float.parseFloat(JOptionPane.showInputDialog(null, "Enter Exam 2 Grade: ")));
// and so on ..
// now add the student to the ArrayList
studentList.add(student);
JOptionPane.showMessageDialog(null, "Final Grade: " + student.getFinalGrade(),
" " + student.getName(), JOptionPane.PLAIN_MESSAGE);
}
EDIT II:
// show the averages here
JOptionPane.showMessageDialog(null, "Avg Grade Of Exam One: " + getAverageGradeOfExamOne(studentList), JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null, "Avg Grade Of Exam Two: " + getAverageGradeOfExamTwo(studentList), JOptionPane.PLAIN_MESSAGE);
// ...
Using this list of students you can now compute whatever you want and it is all well structured and easy to use.
e.g.
private float getAverageGradeOfExamOne(List<Student> studentList) {
float sum;
for(Student student : studentList){
sum += student.getExamOneGrade();
}
return sum/studentList.size();
}
EDIT:
Using this method above in your "original class" in the main-method we are talking about you could print the result this way:
JOptionPane.showMessageDialog(null, "Avg Grade Of Exam One: " + getAverageGradeOfExamOne(studentList), JOptionPane.PLAIN_MESSAGE);
If this does not work I suppose your "main-method" is a static one. Then change getAverageGradeOfExamOne() to static too, like this
private static float getAverageGradeOfExamOne(List<Student> studentList) {
float sum;
for(Student student : studentList){
sum += student.getExamOneGrade();
}
return sum/studentList.size();
}
One of these method declarations should tie up loose ends for you.

Related

how to position this java while loop?

So the while loop is not working, even though it compiles.  How do I position it correctly??
I tried a few things but they kinda worked. if someone on here can help me out that would be great
import java.util.Scanner;
//This is a Driver program to test the external Class named Student
public class StudentDriver //BEGIN Class Definition
{
//**************** Main Method*************************
public static void main (String[] args)
{Scanner scan = new Scanner(System.in);
//Data Definitions:
//Instance Data
String courseName;
int courseCredits;
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
//Executable Statements:
//Initialize first Student
name = "Fred Fergel";
id = "0123";
street = "123 Main Street";
city = "Smalltown";
state = "NY";
zip = "12345";
major = "Computer Science";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
//Test toString
System.out.println("Student 1\n\n" + student1.toString());
//Print a blank line
System.out.println();
//Add a course
student1.addCourse("CSC111", 4);//NOTE:  DO NOT PUT A SPACE BETWEEN CSC AND 111
//Print schedule
System.out.println("Student 1's Schedule:\n\n");
student1.displaySchedule();//call method
final String FLAG = "Y";
String prompt = "Y";
while (prompt.equals("y"))
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);
System.out.println("Do you wish to enter another course? y/n");
prompt = scan.next();
}
//end while
}//end main
}//end StudentDriver
Here is the student class:
import java.util.Scanner;
public class Student
{Scanner scan = new Scanner(System.in);
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
int totalCredits;
final int SIZE = 6;
final int MAX_CREDITS = 18;
String [ ] schedule = new String [SIZE];
int courseNumber = 0; //start out with no courses
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 10 courses
{
System.out.println("You have exceeded 10 courses.");
}//end courseNumber
}//addCourse
//Method to display the schedule
//-------------------------------------------------------
// Will only print out the courses added to the array.
//-------------------------------------------------------
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
}
String prompt = "Y";
while (prompt.equals("y"))
Y and y are not the same thing. You need to use .equalsIgnoreCase() instead of .equals() if you want it to ignore case.

Computing average in a class

right now I am working on a program that is printing out a students name, id number, scores on exams, average score, and grade. For some reason there is a problem with the method that computes the average score. I have tried adding parenthesis and that didn't change the result either. This ultimately messes up the grade because the grade is calculated with the average score. Any help is appreciated, thanks! Here is my code:
import java.util.Scanner;
public class Student {
private String fname;
private String lname;
private int id;
private int score1;
private int score2;
private int score3;
private double average;
private String grade;
public void readInfo()
{
Scanner k = null;
k = new Scanner (System.in);
System.out.println ("Please enter the first name: (Enter John as first name and Doe as last name to stop) ");
fname = k.next();
System.out.println("Please enter the last name: ");
lname = k.next();
if (fname.equalsIgnoreCase("John")&&lname.equalsIgnoreCase("Doe"))
System.exit(0);
System.out.println("Please enter the student ID: ");
id = k.nextInt();
System.out.println("Please enter the first score: ");
score1 = k.nextInt();
System.out.println("Please enter the second score: ");
score2 = k.nextInt();
System.out.println("Please enter the third score: ");
score3 = k.nextInt();
}
//The problem lies in here:
private void computeAverage()
{
average = score1+score2+score3/3.0;
}
private void computeGrade()
{
if (average>=90&&average<=100)
grade = "A";
else if (average>=80&&average<=89.9)
grade = "B";
else if (average>=70&&average<=79.9)
grade = "C";
else if (average>=60&&average<=69.9)
grade = "D";
else
grade = "F";
}
private String getName()
{
return fname + " " + lname;
}
private double getAverage()
{
return average;
}
public void printAll()
{
System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
System.out.println();
System.out.println("-----------------------------------------------------");
System.out.printf("%-9s%-9s %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
System.out.println();
System.out.println("-----------------------------------------------------");
}
}
I guess the problem is because, you are not initializing the variable average anywhere.
Though, you have a method computeAverage(). Its not been called from anywhere in the program. Probably, you might also do it anywhere outside.
And please include parenthesis which will definitely produce the correct result.
Order of operations. What you are doing is sum 1 + sum 2 plus the quotient of sum3 and 3. When you divide, you must divide by exactly what you need to be divided. You should be doing (sum 1+ sum 2+ sum 3)/3
If you don't want to divide by 2, you can also multiply by one half, that won't change anything, but it's just another option.
(sum 1+ sum 2+ sum 3)*1/2
Keep in mind what you want to divide. If it is more term, take advantage of grouping symbols!
{Rich}

How to use loops and average in Java [duplicate]

This question already has answers here:
How to get average from given values
(3 answers)
Closed 9 years ago.
My program is supposed to find the average of female, male, and total average GPA of students. And also total female, male, and total students. First it asks if the student is male or female. If you choose male it does the loop, but after it ends. I want my program to go straight into the next choice. Example if you choose male the you'll input female and visa versa.
import java.util.Scanner;
public class practice {
public static void main(String [] args) {
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
System.out.println("Enter GPA");
GPA = keyboard.nextDouble();
if (student.equals("M")) {
while (GPA >=0) {
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
}
if (student.equals("F")) {
while (GPA >=0) {
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
}
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
allAverage = mTotal + fTotal;
totalStudents = maleCount + femaleCount;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total MALE Average GPA: " + mAverage);
System.out.println("Total average: " + allAverage);
}
}
How to use loops and average in Java?
Well, pretty much as in the code in your question, I'd say. Just add a loop around the part that needs a loop, and figure out how you are going to end the looping.
The other problems that leap out at me are:
You seem to be accepting the input in a strange order.
You are calculating allAverage incorrectly. Just look at the code again. The problem should be obvious.
Actually, one of the difficulties with answering this Question is that it is not at all clear how the program as written is supposed to behave. And we can't infer that from what you've shown us. 'Cos what you've written obviously doesn't work ... from a usability perspective.
If you don't understand and can't explain the requirements properly, there is not much chance that you will be able to implement them correctly.
Fixed my code sorry for it being unclear.
import java.util.Scanner;
public class practice
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents, count = 0;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
do{
System.out.println("Enter GPA " + student);
GPA = keyboard.nextDouble();
if (student.equals("M"))
{
while (GPA >=0)
{
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
student = "F";
}
else if (student.equals("F"))
{
while (GPA >=0)
{
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
student = "M";
}
}
while (++count < 2);
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
totalStudents = maleCount + femaleCount;
allAverage = (mTotal + fTotal)/totalStudents;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total average: " + allAverage);
}

Java: coding that uses a variable to specify array length?

I am working on a student scores application that accepts the last name, first name and score for one or more students and stores the results in an array. Then it prints the students and their scores in alphabetical order by last name. We do not know how many students there are, but there will be fewer than 100.
We have to display the class average at the end of the student information and display a message after each student whose grade is more than 10 points below the class average.
My first issue is that I have created a do/while loop to ask if the user would like to enter another but it will not work!?!?
Second, I can not figure out how to display the "10 points below" message on individual students.
public class Student implements Comparable
{
String firstName;
String lastName;
int score;
//stores last name, first name and score for each student
public Student(String lastName,String firstName,int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.score = score;
}
//implement the comparable interface so students can be sorted by name
public int compareTo(Object o)
{
Student otherStudent = (Student)o;
if(otherStudent.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(otherStudent.firstName);
}
else
{
return lastName.compareToIgnoreCase(otherStudent.lastName);
}
}
public String toString()
{
return lastName + ", " + firstName + ": " + score;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class StudentApp
{
static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
Student [] studentArray;
String lastName;
String firstName;
int score = 0;
double average = 0;
System.out.println("Welcome to the Student Scores Application.");
System.out.println();
do{
//code that uses variable to specify the array length
int nStudent = 100; //array size not set unit run time
studentArray = new Student[nStudent];
for (int i=0; i<nStudent; i++)
{
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
studentArray[i] = new Student(lastName, firstName, score);
double sum = 0.0;
sum += score;
average = sum/nStudent;
}
}while (getAnotherStudent());
Arrays.sort(studentArray);
System.out.println();
for (Student aStudent: studentArray)
{
System.out.println(aStudent);
if (score<= (average-10))
{
System.out.println ("Score 10 points under average");
}
}
System.out.println("Student Average:" +average);
}
public static boolean getAnotherStudent()
{
System.out.print("Another student? (y/n): " );
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
}
}
There are a few problems here:
Every time through the do...while, you reinstantiate studentArray and sum. This means that all of your previously iterated over data is nuked when getAnotherStudent() is true - you want to instantiate the array and sum only once.
You don't stop if you have more than 100 students. You need an ending condition around nStudent as well in your loop.
You should make a few adjustments to getAnotherStudent() so that you can block on data, and wait when valid data is input - by using a loop:
public static boolean getAnotherStudent() {
Scanner sc = new Scanner(System.in);
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) {
String choice = sc.next();
// blocks here - ignores all input that isn't "y" or "n"
while(!((choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("N")))) {
if (choice.equalsIgnoreCase("Y")) {
return true;
}
System.out.print("Another student? (y/n): " );
choice = sc.next();
}
}
return false; // obligatory
Your code is close there are just a couple of problems. The reason why your do while loop is not working is that you have a for loop inside of it. This means that you will ask for 100 students before you ask if they want to add another one. Your sum is being created inside this loop so it will be reset each time.
Finally you do not know how many Students will be added but your code assumes there will be 100 Students. This means you cannot use the for each loop to go through the array as some could be null. Just use a regular for loop going up to the last index of a student you added. Here are the changes:
Student[] student = new Student[nStudent];
int studentCount = 0; //declear the counter outside the loop
double sum = 0.0; //declear the sum outside the loop
do {
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
student[studentCount] = new Student(lastName, firstName, score);
sum += score; //increase the sum
studentCount++; //increment the counter
} while (studentCount < nStudent && getAnotherStudent()); //stop if the user says 'n' or we hit the maximum ammount
average = sum / studentCount; //work out the average outside the loop
System.out.println();
for (int i= 0; i< studentCount; i++ ) {
System.out.println(aStudent);
if (score <= (average - 10)) {
System.out.println("Score 10 points under average");
}
}
System.out.println("Student Average:" + average);
}
Your getAnotherStudent() method should read:
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) { // blocks until user entered something
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
} else {
// won't come here
return false;
}

How do I write a method to calculate total cost for all items in an array?

I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}

Categories