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

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;
}

Related

JOptionPane inputs to array for mean

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.

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.

Displaying details of object arrays

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();
}

Print array at given position

I am trying to print out two arrays at given position.
The program has two parts. One where the user is asked to enter a string(student name) and an int (student grade) at the end the user is asked to search for the name entered and to print out the student name and the grade
So far I cant't print any.
This is my code for populating the arrays...
System.out.println("Please Enter The Number Of Students In The Class!!");
int numberOfStudents = input.nextInt();
String []studentNames = new String[numberOfStudents];
int [] StudentGrades = new int[numberOfStudents];
int i;
for (i =0; i<numberOfStudents; i++)
{
System.out.println("Enter Student Name!");
studentNames[i]= input.next();
System.out.println("_________________");
System.out.println("Enter Student Grade");
StudentGrades[i] = input.nextInt();
System.out.println("_________________");
}
... and this for searching the name:
Scanner input = new Scanner(System.in);
String nameInput = input.next();
int cheak;
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
cheak++;
}
}
if (cheak !=0)
{
System.out.println("Name Found ");
}
else
{
System.out.println("Name Not Found");
}
Now I want to print the student name that is entered in the search with the corresponding grade.
How do I accomplish that?
You have to just keep a record of the index of target name in the studentNames array.
You can modify the loop in the following way to get the index in the cheak variable -
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
break;
}
cheak++;
}
if (cheak != numberOfStudents)
{
System.out.println("Name Found. Name = " + studentNames[cheak] + " Grade = " + StudentGrades[cheak]);
}
else
{
System.out.println("Name Not Found");
}
try the following:
for ( String student : studentNames) {
if (nameInput.equals(student)) {//if the student is found, stop the loop
break;
}
cheak++;
}
if (cheak != studentNames.length){
System.out.println("Name Found ");
System.out.println("The name is: " + studentNames[cheak]);
System.out.println("Grade is: " + studentGrades[cheak]);
} else {
System.out.println("Name Not Found");
}

for loop class assignment gone wrong

I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}

Categories