• 0

Help with Assignment - Java - Student Class


Question

public class Student{
   private String name; 
   private double myQuizScore;
   private int quizNum = 0;
   public Student(String studentName, double quiz, int initialQuizNum){ 
   name = studentName; 
   myQuizScore = quiz; 
   quizNum = initialQuizNum;
    } 
   public String getName(){            //get the name of the student (Anthony L)
    return name;                       
    }
   public double getQuizScore(){       //The score that Anthony got in his quizzes
    return myQuizScore;
    }
   public int getQuizNum(){            //The number of quizzes taken
    return quizNum;
    }
    
    public void addQuiz(int score){    //To add score toward multiple quizzes and also the quizzes taken
      myQuizScore += score;
      quizNum ++;
    }
    
    public double getAverageScore(){   //Getting average quiz score by diving the overall amount of quizzes taken
      return myQuizScore / quizNum;
    }

} 
 
 
---------
 
import java.util.Scanner;
import java.io.*;

public class StudentTester{

   public static void main(String[] args) {
   
   Scanner in = new Scanner(System.in);
   System.out.print("Enter a number in the range of 0 - 100: ");       
   int num1 = in.nextInt();
   if (num1 <= 0){
   System.out.println("Please only enter a number between 0 - 100.");
   }
   
   final int QUIZ1 = 70;                                                         //Use constant number instead of magic number for quiz 1
   final int QUIZ2 = 80;                                                         //Use constant number instead of magic number for quiz 2
   final int BASE_TOTAL_SCORE = 90;                                              //Use constant number for Total score instead of magic number
   final int BASE_QUIZ_NUM = 1;                                                  //Use constant number for quizzes taken instead of magic number
   
   Student Anthony = new Student ("Anthony L", BASE_TOTAL_SCORE, BASE_QUIZ_NUM); //Displaying Name, Total Score, Quiz taken       
         
   System.out.println("Name: " + Anthony.getName());                             //Print Name
   System.out.println("Quiz score: " + Anthony.getQuizScore());                  //Print quiz score
   
   Anthony.addQuiz(QUIZ1);                                                       //Add quiz1
   Anthony.addQuiz(QUIZ2);                                                       //Add quiz2
   
   System.out.println("Number of Quizzes: " + Anthony.getQuizNum());             //Print number of quizzes taken
   System.out.printf("Average score: %.2f", Anthony.getAverageScore());          //Print average score of the quizzes
   }
}

 
Above are my codes
So here are the instruction that i am confuse at:
takes in a Scanner object passed in from main()                  -  is this correct for me to put the code in the StudentTester?
It must read a number into an integer variable unless a non-number value is entered, in which case the 
method will return false. You may use try/catch or an if statement for this.           -     I tried to look up for try/catch statement and i try to apply it but still do not get it instead it messes up everything so can you help
If the datum/score seems acceptable, the addGrade method must be called.                     
If addGrade returns false, then inputData should throw an IllegalArgumentException or return false              -     so for sure the try/catch statement need to work first but afterward, when it work should i assume we use if statement and how to throw IllegalArgumentException or return false
 
 

 

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

So here are the instruction that i am confuse at:

takes in a Scanner object passed in from main()                  -  is this correct for me to put the code in the StudentTester?

Without seeing the assignment as a whole it's hard to say, but it Sounds like it wants you to pass the Scanner object to another class or function. Perhaps it would be better to separate the entry point from the StudentTester class.

 

public class StudentApp {

	public static void main ( String[] args ) {
		Scanner input = new Scanner ( System.in );
		Test = new StudentTest ();
		Test.run ( input );
	}
}

class StudentTest {

	public void run ( Scanner input ) {
		
		String 	name 	= input.nextLine ( "Please enter Student's name." );
		int 	score 	= input.nextInt  ( "Please enter Student's score." );
		
		Student result = new Student ( name, score, ... );
		...
	}
}
Or you could keep it in a single class and make 'run' a static function. Separation of concerns should apply though.

 

It must read a number into an integer variable unless a non-number value is entered, in which case the 

method will return false. You may use try/catch or an if statement for this.           -     I tried to look up for try/catch statement and i try to apply it but still do not get it instead it messes up everything so can you help

It means either:

 

int score = 0;
try { 
	score = input.nextInt ( "Please enter student's score" );

} catch ( InputMismatchException e ) {
	System.out.println ( "Invalid score." );
	return false;
}
or this:

 

int score = 0;
if ( !input.hasNextInt() )
	System.out.println ( "Invalid score." );
	return false;
else { 
	score = input.nextInt();
}
The assignment wants you to test for an invalid input case. Whether you catch an exception or test for a matching input is a question of optimistic or pessimistic approach. In both instances, it handles an invalid input and responds accordingly.

 

If the datum/score seems acceptable, the addGrade method must be called.                     

If addGrade returns false, then inputData should throw an IllegalArgumentException or return false              -     so for sure the try/catch statement need to work first but afterward, when it work should i assume we use if statement and how to throw IllegalArgumentException or return false

Again, it's hard to say without seeing the assignment. You're talking in abstracts without giving us the full details.

Actually throwing an exception isn't hard:

throw new IllegalArgumentException ( "Invalid grade" );
Link to comment
Share on other sites

  • 0

Attach is the actual information, I tried using your code but it resulted in a lot of errors and i need to have StudentTester.java and Student.java

 

I need help for the Version 2 I have done part of them but I am having trouble in most of them and still confuse where to put the code whether it is on StudentTester.java or Student.java

P2 cs141.pdf

Link to comment
Share on other sites

  • 0

Attach is the actual information, I tried using your code but it resulted in a lot of errors and i need to have StudentTester.java and Student.java

Yeah I didn't test that code. It was just for example purposes.

 

I need help for the Version 2 I have done part of them but I am having trouble in most of them and still confuse where to put the code whether it is on StudentTester.java or Student.java

You'll probably want something like this:

import java.util.*;

public class StudentTester {

	public static void main ( String[] argv ) {

		Scanner input = new Scanner ( System.in );
		
		Student firstStudent	= new Student ( "Atyemail" );
		Student secondStudent	= new Student ( "Second Student" );
		Student thirdStudent	= new Student ( "Third Student" );
		
		doQuiz ( input, firstStudent, 5 );
		doQuiz ( input, firstStudent, 5 );
		
		doQuiz ( input, secondStudent, 1 );
		doQuiz ( input, thirdStudent,  1 );
	 
	}

	private static void doQuiz ( Scanner input, Student subject, int numQuizes ) {
		
		int i = 0;
		while ( i < numQuizes ) {
		
			System.out.format ( "Please enter student %s's score ( 0 - 100 ) for quiz no.%d%n", subject.getName (), i + 1 );
			
			try { 
				if ( !subject.inputData ( input ) ) {
					/* consume the line */
					input.nextLine ();
					System.out.println ( "Invalid input. Please enter an integer between 0 and 100." );
					continue;
				}
				i++;
			} catch ( IllegalArgumentException e ) {
				System.out.println ( e.toString () );
			}
		}		
		
		System.out.println ( subject.toString() );
	}
}

enum Grade {

	A ( 90, 100 ), B ( 80, 89 ), C (70, 79), D ( 60, 69 ), F ( 0, 59 );

	private final int min, max;

	private Grade ( int min, int max ) {
		this.min = min;
		this.max = max;
	}	

	public static boolean isValidScore ( int score ) {
		return score <= A.max && score >= F.min; 
	}

	public static Grade scoreToGrade ( int score ) {
		
		for ( final Grade grade : values () ) {
			
			if ( score >= grade.min && score <= grade.max )
				return grade; 
		}

		return null;
	}
} 

class Student {
	
	private int	numberOfElements= 0;
	private int	highValue	= 0;
	private int	lowValue	= 0;
	private int	sumOfData	= 0;
	private int	sumOfSquares	= 0;
	private int	a = 0, b = 0, c = 0, d = 0, f = 0;
	private String	scoresEntered	= "";
	private String	name		= "";

	public Student (){};
	public Student ( String name ) {
		this.name = name;	
	}
	
	public boolean inputData ( Scanner in ) {		

		if ( !in.hasNextInt () )
			return false;

		if ( !addGrade ( in.nextInt () ) )
			throw new IllegalArgumentException ( "Invalid grade" );

		return true;
	}

	public boolean addGrade ( int score ) {
		
		if ( !Grade.isValidScore ( score  ) )
			return false;
		
		if ( 0 == numberOfElements ) {
			highValue = score;
			lowValue  = score;
		}		
		
		switch ( Grade.scoreToGrade ( score ) ) {
		case A:
			a++;
			break;
		case B:
			b++;
			break;
		case C:
			c++;
			break;
		case D:
			d++;
			break;
		case F:
			f++;
			break;
		}	
	
		if ( score > highValue )
			highValue = score;
		
		if ( score < lowValue )
			lowValue = score;
		
		numberOfElements++;
		sumOfData	+= score;
		sumOfSquares  	+= score * score;
		scoresEntered 	+= Integer.toString ( score ) + ",";

		/*	unnecessary and inefficient to calculate and store mean for each addGrade. 
			Call calculate once in toString instead. 
		calculate (); 
		*/

		return true;	
	}

	private double getMean () {
		return ( double ) sumOfData / numberOfElements;
	}

	/* v = ? [(xi - x?)2] / n - 1; */ 
	private double getVariance () {

		if ( 1 >= numberOfElements )
			return 0;
			
		return ( sumOfSquares - getMean () ) / ( numberOfElements - 1 ); 
	}

	private double getStd () {
		return Math.sqrt ( getVariance () );
	}

	public String toString () {
		
		String out = String.format ( "Quizes:%01d Total score:%01d%nRange:%01d-%01d Mean:%01.3f%n%01d A's %01d B's %01d C's %01d D's %01d F's%n",  
			numberOfElements, sumOfData, lowValue, highValue, getMean(), a, b, c, d, f );

		/* extra credit */
		out += String.format ( "*Extra credit%nSum of Squares:%01d Variance:%01.3f Average (sans lowest):%01.3f Std Deviation:%01.3f%n",  
			sumOfSquares, getVariance(), ( double ) ( ( sumOfData - lowValue ) / numberOfElements ), getStd() );

		return out;
	}

	public String getName () { return name; }
}
It will probably need a few tweaks to meet all the assignment requirements, but it's a start.
Link to comment
Share on other sites

This topic is now closed to further replies.