简体   繁体   中英

Having lots of trouble with classes in Java

I'm learning how to use classes and methods, but nothing can get through to me. I've read the sections in the textbook and plenty of webpages. I am writing a program in Java that will take grades from 2 quizzes, a midterm, and a final, and spit out all the grades, the final weighted grade, and a letter grade. I've tried many times, but couldn't do it using classes. I was able to code a program that works without implementing classes, but I REALLY want to know about classes.

This is how I did it without classes:

import java.util.Scanner;

public class grade {
    public static void main(String args[]) {


        //quiz method       
        Scanner keyboard = new Scanner(System.in);
        System.out.printf("Please enter the grade of Quiz 1: ");
        double a = keyboard.nextInt();

        System.out.printf("Please enter the grade of Quiz 2: ");
        double b = keyboard.nextInt();

        double c = (a + b);
        double d = (c / 20);
        double quizGrade = (d * 25);


        //midterm method
        System.out.printf("Please enter the grade of the Midterm: ");
        double aa = keyboard.nextInt();
        double bb = (aa / 100);
        double midtermGrade = (bb * 25);


        //final method
        System.out.printf("Please Enter the grade of the Final: ");
        double aaa = keyboard.nextInt();
        double bbb = (aaa / 100);
        double finalGrade = (bbb * 50);

        double overallGrade = (quizGrade + midtermGrade + finalGrade);

        System.out.printf("Score for Quiz 1 is: %f\n", a);
        System.out.printf("Score for Quiz 2 is: %f\n", b);
        System.out.printf("Score for Midterm is: %f\n", aa);
        System.out.printf("Score for Final is: %f\n", aaa);


        //figuring letter grade
        if (overallGrade >= 90) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: A\n");
        }
        if (overallGrade >= 80 && overallGrade <= 89) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: B\n");
        }
        if (overallGrade >= 70 && overallGrade<= 79) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: C\n");
        }
        if (overallGrade >= 60 && overallGrade<= 69) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: D\n");
        }
        if (overallGrade < 60) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: F\n");
        }
    }

}

And this is how I tried it with classes... I think it's safe to say I have NO idea what I'm doing:

import java.util.Scanner;

public class grade2 {
    Scanner keyboard = new Scanner(System.in);
    System.out.printf("Please enter the grade of Quiz 1: ");
    double grade1 = keyboard.nextInt();
    System.out.printf("Please enter the grade of Quiz 2: ");
    double grade11 = keyboard.nextInt();
    System.out.printf("Please enter the grade of the Midterm: ");
    double grade2 = keyboard.nextInt();
    System.out.printf("Please enter the grade of the Final: ");
    double grade3 = keyboard.nextInt();

    public static double quizgrade(double grade1, double grade11) {
        //quiz      
        double a = grade1
        double b = grade11

        double c = (a + b);
        double d = (c / 20);
        double quizGrade = (d * 25);
        return quizGrade;
    }

    public static double midtermgrade(double grade2) {
        //midterm
        double aa = grade2
        double bb = (aa / 100);
        double midtermGrade = (bb * 25);
        return midtermGrade;
    }

    public static double finalgrade(double grade3) {
        //final
        double aaa = grade3
        double bbb = (aaa / 100);
        double finalGrade = (bbb * 50);
        return finalGrade;
    }

        double overallGrade = (quizgrade + midtermgrade + finalgrade);

        System.out.printf("Quiz 1 grade is: %f\n", grade1);
        System.out.printf("Quiz 2 grade is: %f\n", grade11);
        System.out.printf("Midterm grade is: %f\n", grade2);
        System.out.printf("Final grade is: %f\n", grade3);


        //figuring letter grade
        if (overallGrade >= 90) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: A\n");
        }
        if (overallGrade >= 80 && overallGrade <= 89) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: B\n");
        }
        if (overallGrade >= 70 && overallGrade<= 79) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: C\n");
        }
        if (overallGrade >= 60 && overallGrade<= 69) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: D\n");
        }
        if (overallGrade < 60) {
            System.out.printf("Your overall grade is: %f\n", overallGrade);
            System.out.printf("Your letter grade is: F\n");
        }
}

Any help? This material is confusing to no end!

Your first goal should be to get your code to execute so you can examine it and get an understanding of what is going on, then you can learn about other aspects of OOP after that.

In your first snippet of code you've wrapped a class around procedural code and since it is inside your static main method, it will execute when you run your program. However, in your second attempt you don't create an instance of the class (object) anywhere, so how can anything execute? There is no main method, so unless you are creating an instance of grade2 somewhere else then your code would never execute.

For an implementation with a single class you would have a static main method inside your grade2 object that creates an instance of itself (I would advise class names with capitalised names) like this:

public class Grade2 {

    static void main(String[] args) {

        Grade2 grade2 = new Grade2(); // Construct (instantiate) the object.

        // Access methods etc. on the grade2 instance.
        grade2.doStuff(args);
    }

    // Other methods etc.
}

So by creating an instance of your class, you can then use the instance (grade2) to call methods and access variables etc. I don't want to overload you with access (public, private, protected) yet. But if you can wrap your head around this then you will start to gain traction on other aspects of OOP.

Good luck!

in OOP when you specify that a method or variable is static than, it is a member of the class. If its not static it is a member of the instance of that class. Also looking into constructors, the first thing that is called when creating a new instance of the class.

ex.

public class grade2{
       static{
         //this is a static block that is only called on the first time an instance of the class is ran
     }
   public grade2(){
         //this is a constructor
       }
}

Ok...I sometimes think this is like riding a bike...you don't 'have it' but once you do, you'll have it for life.

You want to solve this problem using some classes...ok.

First off, break this into two things...a program (the thing that will accept input from a user) and a model (or domain).

Your model is just a series of classes. In really simple terms, lets create a class called

Student a class called Exam

A student might have some fields on it private String name;

and maybe some others, private Exam midterm; private Exam final; private Exam quiz;

create getters and setters for these fields

ok...I hope you're still with me. If this seems easy, try implementing your exam weighting into subclasses for the exams.

Your Exam superclass (if you chose to go the subclass route) has a method called something like getWeightedExamMark or whatever you want to call it. It returns a double and accepts a double in its signature. By subclassing Exam into, say, Final, Midterm and Quiz, that method can be overridden to apply the rules for how much that is worth.

Actually, you should move the three Exam objects of the Student class and into a ReportCard class...then you have a method on the ReportCard of getMark() that tallies up the getWeightedExamMark methods from the three exam subclasses to render the final mark.

I'd write the code but figure it's better to lead you along so you learn the syntax and structure yourself.

Good luck.

Firstl you need to identify the real world object that you need to represent

In your case its Grade ,Test ,User

Test can be of type - Quiz , MidTerm , Final

Each User will be awarded a grade for each type of test

  Class User {

   List<Test> testList ;

   public double getQuizGrade() { .. }
   public double getMidTermGrade() { .. }
   public double getFinalTermGrade() {..} 
   public String getOverAllGrade() { .. }

   }

   Class Test {
   // define an enum of TestType( QUIZ , MIDTERM , FINALTERM)
   Grade g ;

   }

   Class Grade {
   double marks ; 
   }

Now once you have modelled these classes , you can go ahead and add a main method which will capture the grades for each test that a user takes and on calling the appropriate user method computes and gives you the grade

I suggest migrating this to https://codereview.stackexchange.com/ .

Fundamentally classes are models for instances (also called objects). All instances of one class can be used trough the methods this class exposes. Example:

class Color {
  // instance variable
  String name;

  // constructor
  Color(String nameOfColor) {
    name = nameOfColor;
  }
}

Color red = new Color("red");
Color green = new Color("green");

System.out.println(red.name) // prints "red"
System.out.println(green.name) // prints "green"

This is what happened above:

  1. We declared a class Color
  2. We instantiated two objects of the class Color with the names red and green
  3. We used the name method to print the name of the Color

You can see that we used the same method (name) for both colors but got different results. This is because the variables of each instance differ but the model (the class) stays the same.

You did use static methods, they don't have access to the variables (state) of a instance but can be called directly on a class (no instance needed). BUT programming with static methods isn't very object oriented, ie not class-based programming. Its functional programming.

Can go like this:

public class GradesReport{

    //Here you store keyboard input
    private double quizOneGrade;
    private double quizTwoGrade;
    private double midtermGrade;
    private double finalGrade;

    public printAllGrades(){
        //Send all attributtes to standart output
    }


    public getOverallGrade(){
        //Do your algorithm magic here
    }

    // Getters and setters here. If you want some formatting do that there

You instantiate this class with keyboard input from another class that has a main method.

Just for giggles, my refactoring. Not really taken to completion, but set up to show a few ideas like:

  • Constructors
  • Factory method
  • Static and instance methods
  • Handling input/output more cleanly
  • toString() method

Have fun.

import java.io.InputStream;
import java.util.Scanner;

public class Grade2 {

  /** In fractions of available points. */
  final double quiz1Grade;

  /** In fractions of available points. */
  final double quiz2Grade;

  /** In fractions of available points. */
  final double midtermGrade;

  /** In fractions of available points. */
  final double finalGrade;

  Grade2(double quiz1Grade, double quiz2Grade, double midtermGrade,
      double finalGrade) 
  {
    this.quiz1Grade = quiz1Grade;
    this.quiz2Grade = quiz2Grade;
    this.midtermGrade = midtermGrade;
    this.finalGrade = finalGrade;
  }

  /** returns a final grade in percentage points. */
  public double overallGrade()
  {
    // weighted sum out of 100
    return ((quiz1Grade + quiz2Grade) * 25) + 
           (midtermGrade * 25) +
           (finalGrade * 50);
  }

  private static String letterGrade(double overallGrade)
  {
    final String letter;
    //figuring letter grade
    if (overallGrade >= 90) {
        letter= "A";
    } else if (overallGrade >= 80 && overallGrade <= 89) {
      letter= "B";
    } else if (overallGrade >= 70 && overallGrade<= 79) {
      letter= "C";
    } else if (overallGrade >= 60 && overallGrade<= 69) {
      letter= "D";
    } else if (overallGrade < 60) {
      letter= "F";
    } else {
      letter = "UNKNOWN "+overallGrade;
    }
    return letter;
  }

  public void reportGrade()
  {
    double overallGrade = overallGrade();
    String letter = letterGrade(overallGrade);
    System.out.printf("Your overall grade is: %f\n", overallGrade);
    System.out.printf("Your letter grade is:" + letter + "\n");
  }

  @Override
  public String toString()
  {
    return String.format("Score for Quiz 1 is: %f\n", quiz1Grade) +
    String.format("Score for Quiz 2 is: %f\n", quiz2Grade) +
    String.format("Score for Midterm is: %f\n", midtermGrade) +
    String.format("Score for Final is: %f\n", finalGrade);    
  }

  public static Grade2 readGradeFrom(final InputStream in)
  {
    Scanner keyboard = new Scanner(in);
    System.out.printf("Please enter the grade of Quiz 1: ");
    int quiz1 = keyboard.nextInt();
    // in points out of 10

    System.out.printf("Please enter the grade of Quiz 2: ");
    int quiz2 = keyboard.nextInt();
    // in points out of 10

    //midterm method
    System.out.printf("Please enter the grade of the Midterm: ");
    int midterm = keyboard.nextInt();
    // in points out of 25

    //final method
    System.out.printf("Please Enter the grade of the Final: ");
    int finalTest = keyboard.nextInt();
    // in points out of 100

    return new Grade2( quiz1 / 10.0, quiz2/10.0, midterm / 25.0, finalTest / 100.0);
  }



  public static void main(String args[]) 
  {
    Grade2 grade = readGradeFrom(System.in);
    grade.reportGrade();
  }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM