-2

For an assignment, I had to make a class that would accept fractions, but whenever I try to reference the methods in the program I get this error: "Cannot make a static reference to the non-static method". Here's part of my program:

public class Fraction {

  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    String operator;

    System.out.println("What is your numerator?");
    long num = keyboard.nextInt();
    System.out.println("What is your denominator?");
    long denom = keyboard.nextInt();
    System.out.println("Your current fraction is: " + toString());

    keyboard.close(); }

  private long numerator;
  private long denominator;

  public Fraction() {  //constructs fraction 0/1
    numerator = 0;
    denominator = 1; }

  public Fraction(long num){  //constructs fraction n/1
    numerator = num;
    denominator = 1; }

  public Fraction(long num, long denom){  //constructs fraction n/d 
    numerator = num;
    if (denom == 0){  //make sure denom isn't 0
      throw new ArithmeticException(); }
    else{
      denominator = denom; }
    setSign(); } 

  public void add(Fraction fraction){  //addition
    if(fraction.denominator == this.denominator){
     this.numerator += fraction.numerator; }
    else{
      this.numerator *= fraction.denominator;
      this.denominator *= fraction.denominator;
      long temp = fraction.numerator * this.denominator;
      this.numerator += temp; } }   

  public String toString(){  //returns fraction as string
    return (numerator + "/" + denominator); }

  }

How would I access these methods from the main method? Also, how would I call methods like the addition method (what would the code look like)?

Any help is greatly appreciated, thanks!

S. Douglas
  • 13
  • 3

2 Answers2

0

A non-static method means it is a method of a class. In other words, you need to declare a new fraction to call those methods. For example:

Fraction frac = new Fraction(2);
Fraction toAdd = new Fraction(3);
frac.add(toAdd);

Note how the add method is called by using an instance of a fraction, in this case frac (frac.add).

A static method could just be called using Fraction.add, but a non-static method requires you to make an instance of the class first (using new Fraction()).

nhouser9
  • 6,730
  • 3
  • 21
  • 42
  • Do you think you could be a little more specific? Like what exactly would I need to to write to get the output say: "Your fraction is 3/4" using my toString method? – S. Douglas Apr 04 '16 at 07:15
  • Yes. First make a new fraction: Fraction frac = new Fraction(3, 4); Then call the toString: System.out.println(frac.toString()); – nhouser9 Apr 04 '16 at 07:21
0

You are calling toString() instance method without actual instance. You should create object of class Fraction first and call toString() method for the object.

Yaroslav Rudykh
  • 803
  • 6
  • 12