Hi I'm very new to programming and I'm trying to write a programme in eclipse that does the following.
Create a Student class with 4 attributes: name, mark, course and phone number which are entered by the user.
Have a constructor which initialises those four attributes to the parameters passed in, and a display() method which displays the details of the Student.
Declares an empty array of 5 Student objects.
Create a Student object at the current position of the array using these variables.
Make a loop which calls the display() method of each Student in the array.
So far I've got the programme working to the point that it creates the array of 5 students and reads in the four different attributes from the user. But I can not figure out how to create a loop which calls the display method for each of the students.
This is my code so far..
import java.util.Scanner;
public class Student {
private String name, course;
private int mark, number;
public Student(String nameIn, String courseIn, int markIn, int numberIn)
{
this.name = nameIn;
this.course = courseIn;
this.mark = markIn;
this.number = numberIn;
}
public void display()
{
System.out.println("Name: " + this.name + " Course " + this.course + " mark: " + this.mark + " Number " + this.number);
}
public static void main (String[] args)
{
String[] Student = new String[5];
Scanner scanner = new Scanner(System.in);
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter course for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter number for student " + counter);
Student[counter] = scanner.nextLine();
}
for (int counter=0; counter< 5; counter++)
{
System.out.println(Student[counter].display());
}
}
}
PS sorry in advance if I have posted this question wrong. Its my first post and I couldn't find a similar question else where.
Thanks in advance.
Your current code doesn't create an array of Student, nor populate it correctly (each loop overwrites the former data) .
Also, the way you were calling display was wrong :
System.out.println(Student[counter].display());
First, you want to call display on an instance of Student, not on the class.
Second, you don't have to call System.out.println, because displayalready does this work (and calling System.out.println with the void parameter, because the display method returns nothing, will get you nowhere)
Try this way :
Student[] students = new Student[5];
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
String name = scanner.nextLine();
System.out.println("Enter course for student " + counter);
String course = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
String mark = scanner.nextLine();
System.out.println("Enter number for student " + counter);
String number = scanner.nextLine();
Student student = new Student(name, course, mark, number);
students[counter] = student;
}
for (int counter=0; counter< students.length; counter++)
{
students[counter].display();
}
Related
We are asked to write a code and enter name and age for 4 people. After that, we are required to find whether any of the age match each other. Later the question asks whether the names match, but I haven't gotten to that part just yet.
I tried making an array so that I can store the values of the inputted ages. I cannot figure out how I can compare age's values with other elements in the array.
package person;
public class Person
{
static int personAge;
String personName;
public void setName(String name) {
name=personName;
}
public String getName() {
return personName;
}
public void setAge(int age){
age=personAge;
}
public int getAge() {
return personAge;
}
}
package person;
import java.util.Scanner;
public class PersonMain extends Person
{
static int [] ageStore=new int [4];
public static void main(String[] args)
{
for(int i=1;i<5;i++)
{
Person person= new Person();
person.setName(person.personName);
System.out.println("Please enter name for person " + i );
Scanner input= new Scanner(System.in);
person.personName=input.next();
Scanner keyboard= new Scanner(System.in);
System.out.println("Now, input " + person.personName + "'s age" );
person.setAge(personAge);
personAge=keyboard.nextInt();
ageStore[i]=person.personAge;
System.out.println("Age is " + ageStore[i]);
}
//what can help me compare the values of int age in the array?
}
}
The end goal here is to print out the names of people that have the same age.
Of course they all have the same age: personAge is declared as static. Remove the static keyword in front of the declaration.
UPDATE: and yes, use getters and setters instead of accessing fields directly.
To summarise:
remove the static keyword in front of personAge declaration,
declare personAge and personName as private to ensure you use the getters and setters,
remove the extends Person in class PersonMain,
in method main, use the getters and the setters instead of accessing the fields directly.
UPDATE 2: Oh! yes! some more issues:
in the setters, assign the argument to the field, not the other way around (personName=name; and personAge=age).
variable i should go from 0 to 3 because the array is declared with a size of 4: for(int i=0;i<4;i++) or better: for(int i=0;i<ageStore.length;i++),
move the Scanner declaration and initialisation out of the loop, and use only one of them.
If you are collecting information that is required for later processing, you need to store all of that information.
At the moment, you are storing the ages in an array, but throwing away the names.
So, instead of keeping an age array like this:
static int [] ageStore=new int [4];
... try keeping an array of Persons. Plus you don't need to keep them outside the main method. So, in the main method:
Person[] persons = new Person[4];
Also, fix your Person class so that the age is not static and the variables are private:
private int personAge;
private String personName;
Now create a single scanner because you don't need one per loop or per input:
Scanner input= new Scanner(System.in);
Then create your loop, but run it from 0 to less than the length of the array to fill (because indexes in Java start at 0):
for (int i = 0; i < persons.length; i++) {
Then make a new Person object to populate:
Person person = new Person();
Then collect the name and age from the user (remembering that i is 1 less than what you want to show to the user):
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
And add the person to the array:
persons[i] = person;
Then you can close your loop.
So far you should have:
package person;
import java.util.Scanner;
public class PersonMain {
public static void main(String[] args) {
Person[] persons = new Person[4];
Scanner input= new Scanner(System.in);
for (int i = 0; i < persons.length; i++) {
Person person = new Person();
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
persons[i] = person;
}
// matching code will go here
}
}
Now we need to do the matching part.
One way of doing that is to check each item against all the items after it in the list. That would look like this:
for (int i = 0; i < persons.length - 1; i++) { // until 'persons.length - 1' because if we look at the last item, it has nothing left to compare against
Person currentPerson = persons[i];
for (int j = i + 1; j < persons.length; j++) { // start at the next index (i + 1)
if (currentPerson.getAge() == persons[j].getAge()) { // we have an age match
System.out.println(currentPerson.getName() + " has the same age as " + persons[j].getName());
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have figured out how to gather the data from the user to make a new student in my array, but I am having trouble adding that information to the array. Please show me how I can add this data as a new Student object in the given code. Please reference to the AddStudent method.
import java.util.Scanner;
public class ArrayDemo {
static Student[] students;
private static void ViewStudents() {
for (int i = 0; i < students.length; i++) {
System.out.println(i + ") " + students[i].getLName() + ", " + students[i].getFName());
}
}
private static void ViewDetails() {
Scanner kb = new Scanner(System.in);
int i;
System.out.println("Who would you like to view?");
ViewStudents();
i = Integer.parseInt(kb.nextLine());
System.out.println("ANum:\t\t" + students[i].getANum());
System.out.println("\nAddress:\t" + students[i].address.getHouseNum() + " " + students[i].address.getStreet());
System.out.println("\t\t" + students[i].address.getCity() + ", " + students[i].address.getState() + " " + students[i].address.getZip());
System.out.println("\t\t" + students[i].address.getLine2());
}
private static void AddStudent() {
Scanner kb = new Scanner(System.in);
Student student = new Student();
String FirstName;
String LastName;
int HouseNum;
String Street;
String City;
String State;
int Zip;
String Line2;
System.out.println("\tInput Information");
System.out.println("\tFirst Name:");
FirstName = kb.nextLine();
System.out.println("\tLast Name:");
LastName = kb.nextLine();
System.out.println("\tHouse Number:");
HouseNum = Integer.parseInt(kb.nextLine());
System.out.println("\tStreet:");
Street = kb.nextLine();
System.out.println("\tCity:");
City = kb.nextLine();
System.out.println("\tState:");
State = kb.nextLine();
System.out.println("\tZip Code:");
Zip = Integer.parseInt(kb.nextLine());
System.out.println("\tExtra Information:");
Line2 = kb.nextLine();
System.out.println("\nStudent:\t" + LastName + ", " + FirstName);
System.out.println("ANum:\t\t" + student.getANum());
System.out.println("Address:\t" + HouseNum + " " + Street);
System.out.println("\t\t" + City + ", " + State + " " + Zip);
System.out.println("\t\t" + Line2);
//students.setAddress( HouseNum, Street, City, State, Zip, Line2 );
System.out.println("\tYour Student was Successfully Added");
}
private static void RemoveStudent() {
Scanner kb = new Scanner(System.in);
System.out.println("Who would you like to remove?");
ViewStudents();
for (int j = Integer.parseInt(kb.nextLine()); j < students.length - 1; j++) {
students[j] = students[j + 1];
}
students[students.length - 1] = null;
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int x = 40;
//students = new Student[0];
students = new Student[2];
students[0] = new Student("Thomas", "Emily");
students[1] = new Student("Bob", "Joe");
students[0].address = new Address(6614, "White Sands ln", "Hixson", "Tennessee", 37343, "");
students[1].address = new Address(66, "White ln", "Hson", "Tealamabaee", 373873, "");
do {
System.out.println();
System.out.println("Do you want to:");
System.out.println("\t0) View Students");
System.out.println("\t1) View Students' Details");
System.out.println("\t2) Add a Student");
System.out.println("\t3) Remove a Student");
System.out.println("\t4) Exit");
x = Integer.parseInt(kb.nextLine());
switch (x) {
case 0:
ViewStudents();
break;
case 1:
ViewDetails();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
break;
default:
}
} while (x != 4);
}
}
From what I can see, you are using the wrong kind of data structure. You seem to what to add a dynamic number of Students and an ArrayList would be a lot better and more appropriate than an Array. Then you can simply use the add method.
Remember, the size of an Array is immutable (it cannot change) so what you want in this case is definitely some sort of List, probably the ArrayList
If you insist on using an array, you would need to keep track of the number students already added and use that as an index (either as a global variable or pass it in as a parameter). But bear in mind that the nature of an Array means that you will hit a cap very quickly unless you set an very high capacity,
Believe me that there is no way you can add records to array without knowing how many records are there currently in your array. If you don't want another static variable to keep track number of records, you have to loop through the array till it is null.
static int numOfStudents = 0; //declare outside your main
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
if (numOfStudents < students.length){
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[numOfStudents] = stud;
numOfStudents ++;
}
}
An alternative solution which you would prefer. But this is bad in my opinion.
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
int index=0;
while(x<students.length && student[x] != null)
index++; //get position to add new student
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[index] = stud;
}
The easiest way without much change to your code would be to add a class variable called index next to the students array. This variable will keep track of the amount of students since arrays in Java have fixed length:
public class ArrayDemo
{
static Student[] students;
static int index = 0; // keeps track of the amount of students in the students array
// ... rest of your code
Then inside AddStudent() you add all the information you got from input to the current student at the index and update the index:
private static void AddStudent() {
// ... the code where you obtain user information
if(index < students.length) { // make sure there is room to add the user
Student student = new Student(/* add user information into the constructor */);
students[index] = student; // add the user at the index
index++; // update the index
} else {
System.err.println("No more room for students");
}
}
The code above assumes you have a constructor that accepts necessary user information.
Otherwise you can assign the information individually:
Student student = new Student();
student.firstName = firstName;
// ...
Or use setters like:
student.setFirstName(firstName);
If you do not with to use an index to keep track of amount of users and have a more dynamic way of storing the students, then I suggest using a List or some class that extends it such as an ArrayList
Your array has a fixed size of 2 elements. You could instead use a larger MAX value and (as the other answers have hinted) keep a variable that counts the actual number of array indices that are filled.
static int ARRAY_MAX = 10;
static Student[] students;
static int numStudents;
...
students = new Student[ARRAY_MAX];
numStudents = 0;
Adding a student would then look like...
students[numStudents] = new Student();
numStudents++;
...but its going to break when numStudents is greater than equal 10 (ArrayIndexOutOfBoundsException).
In this event you need to enlarge (resize) your array. In Java arrays have fixed size - resizing an array amounts to declaring a brand new array (with increased size), and then copying the old array into the new one. Use System.arraycopy to copy the contents from one array into the other.
You should really just use an ArrayList - behind the scenes this is what that object is doing.
This is an odd situation for me, I just started learning Java OOP.
I made a class looks like this
public class Student {
public static String name;
public static int marks;
public Student(String n, int m){
name = n;
marks = m;
}
public static void printProperties(){
System.out.println("Name = " + name + " , marks = " + m);
}
}
As you can see the constructor accepts two data: name and marks.
in my main method
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].name + ", Marks: " + stu[x].marks);
}
So my output as follows:
Please enter number of students:
2
Please enter name for student #1
tom
Please enter age for student #1
20
Please enter name for student #2
billy
Please enter age for student #2
80
#1 Name: billy, Marks: 80
#2 Name: billy, Marks: 80
It should be:
#1 Name: tom, Marks: 20
#2 Name: billy, Marks: 80
Why is the preceding index value overidding its previous index value?
You code should work absolutely fine, if your Student class looks something like this :
public class Student{
String name;
int marks;
public Student(String name, int marks){
this.name = name;
this.marks = marks;
}
}
EDITED :
This is what Jon Skeet mentioned.
You are using static variables which are class level variables, so they are overridden every time you assign value to them and only the last value is retained.
You need instance variables here.
Do not make your fields static, and let's use private to control access -
public class Student {
private String name; // not static, and use private.
private int marks;
public Human(String n, int m){
name = n;
marks = m;
}
public void printProperties(){ // also should not be static.
System.out.println("Name = " + name + " , marks = " + m);
}
}
Don't use static , simple as that
A static variable belongs to the entire class. It is one variable that is shared among all of the objects. So when you change that variable, it changes it for all the objects.
Instead, define name and marks as instance variables. In other words, remove the static modifier from your variable declarations. An instance variable is unique to each object. Each object has its own copy of an instance variable.
Also, it's good practice to declare name and marks as private. Then create getters and setters for those variables. This hides the implementation.
import java.util.Scanner;
public class Student{
private String name;
private int marks;
public String getName() { //getter
return name;
}
public void setName(String name) { //setter
this.name = name;
}
public int getMarks() { //getter
return marks;
}
public void setMarks(int marks) { //setter
this.marks = marks;
}
public Student(String n, int m){
name = n;
marks = m;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].getName() + ", Marks: " + stu[x].getMarks());
}
scan.close();
}
}
I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}
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;
}