I have this simple project due tomorrow and I'm almost done but the thing is that one of the requirements in class is for it to have an array, a scanner (which I have) and inheritance.
This is what I have so far:
import java.util.*;
import java.io.*;
public class TestScores
{
public static void main(String[] args)
{
System.out.println("Enter scores from a range of 0 to 100.");
System.out.println("");
Scanner kbReader = new Scanner(System.in);
int testscore = kbReader.nextInt();
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
I don't know how to incorporate the array and the inheritance.
What would be the subclass?
Well you could create a Grade Object lets say so you could now have an array of Grade Objects defined as:
Grade[10] grades = new Grade[10]; // 10 Grade Objects can be stored
Then i guess based on your code you could have subclasses of Grade so AGrade, BGrade etc.. and have them contain extra information.
Class Grade {
int mark;
public Grade(int mark){
this.mark = mark;
}
}
Class AGrade extends Grade {
String message = "wooo i got an A";
public AGrade(){
//access mark or message or what ever you want to add here
}
}
I'll leave the rest of the implementation up to you, but you will need to use super access if you want to access the mark in AGrade. It is not clear how much inheritance you have done but if you come from c++ Java does NOT support multiple inheritance.
I might be wrong in what ive said, but it is hard to tell exactly what you are looking for based on the above, i don't see a real need for subclasses here if you are only using a mark and printing out a char.
The example i give uses a message in each Class, so you can show the difference clearly between subclasses.
Related
import java.util.Scanner;
class Average {
int math, programming, oop, total;
public void setGrade(int math, int programming, int oop) {
this.math = math;
this.programming = programming;
this.oop = oop;
this.total = (math + programming + oop) / 3;
}
public int getTotal() {
return total;
}
}
class Remark extends Average {
void remark() {
int totalMark = super.getTotal();
if(totalMark >= 75) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
}
}
class Course extends Average {
void decideCourse() {
int total = super.getTotal();
System.out.println("Average: " + total);
if(total >= 91 && total <= 100) {
System.out.print("Course Offered: \nBSE, BEED, BSAT");
}
else if(total >= 81 && total <= 90) {
System.out.print("Course Offered: \nBSIT, BSCS, BSBA");
}
else if(total >= 75 && total <= 80) {
System.out.print("Course Offered: \nBSITECH, DAT, BSHRM");
}
else if(total < 75) {
System.out.print("Average did!");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int math, programming, oop;
System.out.print("Enter Grade: ");
System.out.print("\nMath: ");
math = sc.nextInt();
System.out.print("Programming: ");
programming = sc.nextInt();
System.out.print("Object-Oriented Programming: ");
oop = sc.nextInt();
Course c1 = new Course();
Remark r1 = new Remark();
c1.setGrade(math, programming, oop);
r1.remark();
c1.decideCourse();
}
}
This problem is related to inheritance. A student need to be graded on the average marks.
In this code class Remark is not extending Average class, when i try to get the total from Average class, its not inheriting.. whats the error here... other parts are working fine
Each Remark (including r1) and each Course (including c1) will have its own copy of all of the fields you define in Average. It is not the case that there is one shared copy of Average; there is one for each instance of Average, and each instance of Remark and Course contains space for all of Average's fields.
No matter what values you enter, r1.remark() will always print "Fail" because you're setting the values in c1 and not r1. Though r1 will inherit the definition of getTotal from Average, you haven't set the values, so they'll all have the default value of 0 and consequently getTotal will return 0.
(Side note: Though it works from a technical standpoint, you might not see cases later where classes like Remark and Course extend a class like Average: You are representing that if some other part of your program needed an Average, you could pass in a Remark or a Course, and that doesn't make as much sense as if (for instance) you had Course, Assignment, and Exam all extend GradableItem. You'll see that principle referred to as the Liskov Substitution Principle.)
So I was given the following GradedActivity class:
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
if (s < 0)
score = 0.0;
else if (s > 100)
score = 100.0;
else
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} }
and I was tasked with generating a constructor that accepts values for points Obtaned and pointsTotal as arguments, initializes them, and sets the corresponding score (points obtained divided by points total), accessors and mutators for pointsobtained and total.
So here is what I came up with:
public class ProgrammingAssignment extends GradedActivity
{
public int pointsObtained;
public int pointsTotal;
public ProgrammingAssignment(int p, int t)
{
pointsObtained = p;
pointsTotal = t;
}
public int getPointsObtained()
{
return pointsObtained;
}
public int getPointsTotal()
{
return pointsTotal;
}
public double getScore()
{
return pointsObtained / pointsTotal;
}
public void setPointsObtained(int p)
{
pointsObtained = p;
}
public void setPointsTotal(int t)
{
pointsTotal = t;
}
}
Everything compiles without error, but getScore isn't computing obtained/total (it comes back 0) in my test class:
public class PADemo
{
public static void main(String[] args)
{
ProgrammingAssignment p1 = new ProgrammingAssignment(28,30);
GradedActivity p2 = new ProgrammingAssignment(0,30);
System.out.println (p1.getPointsObtained());
System.out.println (p1.getPointsTotal());
System.out.println (p1.getScore());
System.out.println (p1.getGrade());
System.out.println (p2.getScore());
System.out.println (p2.getGrade());
p1.setPointsObtained(25);
p1.setPointsTotal(40);
System.out.println (p1.getScore());
System.out.println (p1.getGrade() == 'F');
}
}
How do I obtain the score (points obtained/points total) with getScore()
Test class returns:
28
30
0.0
F
0.0
F
0.0
true
Cars waiting: [a A123TR, a Z23YTU, a R23EWQ, a ERW345, a B12GFT...
Does that look correct? Why would you have the "a " at the beginning? That is not part of the car license. The "a " and "d " need to be removed BEFORE you add the license to the garage or queue.
creates a stack for cars in a garage (Max of 7)
a queue for cars waiting (max of 5)
Your basic logic appears wrong (to me).
When you get an "a" you do one of two things:
if there are less than 7 cars in the garage you add the car to the garage.
If there are 7, then if then are less the 5 cars in the queue, you add the car to the "queue".
When you get a "d" you:
first remove the car from the "garagee",
then you check the "queue". If there are cars in the "queue" then you move the car from the "queue" to the "garage".
So the logic might be structure something like:
while (...)
{
...
String[] data = line.split(" ");
if (data[0].equals("a"))
processArrival( data[1] );
else if (data[0].equals("d"))
processDeparture( data[1] );
}
I used the String.split(...) method which was suggested in your last question because it is a better test then to test the whole String for a specific character and your two pieces of data are separated into the array ready for processing. The data will now be split into two pieces of data: a) function
b) license
I used separate methods because the code is easier to read and logic for each function is contained in individual methods.
I need to take this "over" statement under the overallmethod as finalmethods' parameter, how can I do this. I want to learn the final letter but to do that I want to access over statement.
public static void overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade){
double quizzes = ( ((quiz1*10) + (quiz2*10) + (quiz3*10)) *25) /300;
double finalg = ( grade * 40) / 100;
double mid = (midterm * 35) / 100;
double over = quizzes + finalg + mid;
System.out.println("Your overall score is: " + over);
}
public static void finalmethod(double over){
if(over <= 100 && over >= 90){
System.out.println("Your final letter is: A");
}
else if(over >= 80) {
System.out.println("Your final letter is: B");
}
else if (over >= 70) {
System.out.println("Your final letter is: C");
}
else if (over >= 60) {
System.out.println("Your final letter is: D");
}
else{
System.out.println("Your final letter is: F");
}
}
You're going to need to return the variable over and change your return type to double.
public static double overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade)
{
//Your code
return over;
}
Then simply pass the value returned from the overallmethod to finalmethod.
over is not a statement, it is a local variable now. Just make it class attribute:
public static double over
Make your overall function return the value of over. Then just call the overall function inside the parameter list of finalmethod
The best solution would be to declare over as a private int outside both the methods, i.e. it should have visibility to all the methods in that class (class variable).
Now compute the overall score in the overallMethod and store it to the over variable.
Next, make a public method getOver() which returns the value of over, and call finalMethod in this way : ClassName.finalMethod(objectOfClass.getOver())
By changing the return type of your method to double, and then passing the value in that method to the final method.
I'll copy/paste the assignment, and then the progress I've made thus far. I'm truly not looking for someone to do the assignment, only some assistance to point me in the right direction as to where I'm going wrong? The program is running without error, however it's returning multiple results for a student when it should only be returning one. I can modify the grades and have it produce different results, so I know the math is being done, however I don't know why it's giving multiple (and different) results for a single student. I have been going over the code and cannot determine where I'm going wrong. My best guess is that it's somewhere in the OutputGrade method, I just can't find it.
Instructions:
Create a Java class called student with the following instance variables:
• private String studentName;
• private int [] grades; //an array of grades
Include setter and getter methods to set and get these 2 properties. The setter method for the grades instance array variable — setGrades() — should take a single argument which is an array of int with the grades already filled in. setGrades() should be used if statement(s) to make sure that each grade value in the array parameter is valid (between 0 and 100) — you will need to use a loop in conjunction with the if-statement(s) to do this efficiently. If a grade is out of bounds, setGrades() should set that grade value to 0. The array that you pass to setGrades() must hold between 3 and 5 grades.
Include a method called outputGrade() that averages up all the grades in the student grades array and then uses a switch statement to output grade conversions based on the following criteria:
• For values from 0–59, your program should output: “Student has failed this class”
• For values from 60–69, your program should output: “Student gets a D”
• For values from 70–79, your program should output: “Student gets a C”
• For values from 80–89, your program should output: “Student gets a B”
• For values from 90–100, your program should output: “Student gets an A”
Where “Student” is the actual name of the student.
Create a test class called TestStudent that instantiates 3 students and sets their names and grades and then calls outputGrade() for each student. For your 3 students, 1 must have 3 grades, 1 must have 4 grades, and 1 must have 5 grades. This is so you will have 3 different array sizes to pass to setGrades(). Make sure that for 1 student, setGrades() is called with 1 grade value that is out of bounds (less than 0 or greater than 100).
Code:
public class TestStudent {
public static void main(String[] args) {
Student student1 = new Student();
int[] grades1 = {15, 50, 5};
student1.setStudentName("Ernest Craft");
student1.setGrades(grades1);
student1.outputGrades();
Student student2 = new Student();
int[] grades2 = {95, 95, 95, 95};
student2.setStudentName("Steve Jones");
student2.setGrades(grades2);
student2.outputGrades();
Student student3 = new Student();
int[] grades3 = {105, -1, 72, 90, 88};
student3.setStudentName("Mary Smith");
student3.setGrades(grades3);
student3.outputGrades();
} // end method main
} // end class TestStudent
Student class:
public class Student {
private String studentName;
private int[] grades;
//constructor
public Student() {
}
public void setStudentName(String name) {
studentName = name;
} // end method setStudentName
public String getStudentName() {
return studentName;
} // end method getStudentName
public void setGrades(int gradeArray[]) {
grades = gradeArray;
for (int i = 0; i < gradeArray.length; i++) {
if (gradeArray[i] < 0 || gradeArray[i] > 100) {
gradeArray[i] = 0;
} // end if
} // end loop
} // end method setGrades
public int[] getGrades() {
return grades;
} // end method getGrades
public void outputGrades() {
int gradesTotal = 0;
int gradesAverage;
char letterGrade;
for (int i : grades) {
gradesTotal += i;
} // end loop
gradesAverage = gradesTotal / (grades.length);
if (gradesAverage >= 0 && gradesAverage <= 59) {
letterGrade = 'F';
} else if (gradesAverage >= 60 && gradesAverage <= 69) {
letterGrade = 'D';
} else if (gradesAverage >= 70 && gradesAverage <= 79) {
letterGrade = 'C';
} else if (gradesAverage >= 80 && gradesAverage <= 89) {
letterGrade = 'B';
} else {
letterGrade = 'A';
} // end if statement
switch (letterGrade) {
case 'A':
System.out.println(studentName + " gets an A.");
case 'B':
System.out.println(studentName + " gets an B.");
case 'C':
System.out.println(studentName + " gets an C.");
case 'D':
System.out.println(studentName + " gets an D.");
case 'F':
System.out.println(studentName + " gets an F.");
} // end switch
} // end method outputGrades
} // end class Student
Thanks for taking a look!
Ben
You forgot the break statements from your switch. If you don't break, it'll just keep executing everything until the end of the block!
This somewhat confusing "feature" is a leftover from C, and in most cases you'll want to end all your cases with a break, return or throw.
I'm trying to work on a Java assignment. This is what it asks:
Write a class named TestScores. The class constructor should accept an array of the test scores as its argument. The class should have a method that returns the average of the test scores. If an test score in the array is negative or greater than 100, the class should throw an IllegalArgumentException. Demonstrate. I need a file named TestScores and TestScoresDemo.
This is what I have so far. I know some of it is wrong and I need help fixing it:
class TestScores {
public static void checkscore(int s) {
if (s<0) throw new IllegalArgumentException("Error: score is negative.");
else if (s>100) throw new IllegalArgumentException("Error Score is higher then 100");
else if (s>89)throw new IllegalArgumentException("Your grade is an A");
else if (s>79 && s<90)throw new IllegalArgumentException("Your grade is an B");
else if (s>69 && s<80)throw new IllegalArgumentException("Your grade is an C");
else if (s>59 && s<70)throw new IllegalArgumentException("Your grade is an D");
else if (s<60)throw new IllegalArgumentException("Your grade is an F");
{
int sum = 0; //all elements together
for (int i = 0; i < a.length; i++)
sum += a[i];
}
return sum / a.length;
}
}
class TestScoresDemo {
public static void main(String[] args) {
int score = 0;
Scanner scanner = new Scanner(System.in);
System.out.print(" Enter a Grade number: ");
String input = scanner.nextLine();
score = Integer.parseInt(input);
TestScores.checkscore(score);
System.out.print("Test score average is" + sum);
}
}
I know the assignment calls for a try statement because in my book that's what I see with the IllegalArgumentException. Can anyone help me? I'm using Eclipse as an IDE.
Your TestScores class should have two members: a constructor that accepts an array of scores and a method that returns the average of the scores. The assignment isn't totally clear as to which of these should throw an IllegalArgumentException if a test score is out of range, but I'd make it the constructor (since that's what has the argument).
public class TestScores {
public TestScores(int[] scores) throws IllegalArgumentException {
// test the scores for validity and throw an exception if appropriate
// otherwise stash the scores in a field for later use
}
public float getAverageScore() {
// compute the average score and return it
}
}
You're on the right track with your TestScoresDemo class. It will first need to collect a set of scores into an array. Then it should construct a TestScores object. This is what needs to be inside a try/catch block because it can throw an exception. Then you just need to call getAverageScore() and do something with the result.
An exception is something used to define something that didn't go right on the normal flow of an application. You have to throw the IllegalArgumentException when the method checkScore is called and it finds any argument outside the range (between 0 and 100).
Your class should have this structure:
public class TestScore {
private int scores[]; //With setters and getters.
public TestScore(int scores[]) {
//Here, you set the scores array to the one on this class.
}
public int getAverage() {
//You do the average here, and since you need to iterate over the
//array to sum each value, you can check the value and if it's not
//ok you throw the IllegalArgumentException. No throws keyword
//required since this kind of exception (like NullPointerException
//and many others) are unchecked exceptions, meaning they can be
//thrown by a method and it does not need to specify them.
}
}
The test class should create a TestScore object with an int array as a parameter of its constructor. Then you make a testAverageScore method that has the try-catch statement on it, since it's required to call the getAverage method.
Hope that helps. Good luck!.
EDIT: IllegalArgumentException is an unchecked exception.
public class TestScores {
private final int[] scores;
public TestScores(int[] scores) {
this.scores = scores;
}
public int getAverage() {
int sum = 0;
if(scores.length == 0) {
return 0;
}
for(int score: scores) {
if(score < 0 || score > 100) {
throw new IllegalArgumentException("Score is not valid!");
}
sum += score;
}
return sum/scores.length;
}
}