-2

enter image description here

I am a new learner in java, and I cannot figure out this error. I've already created a class outside the Main class, why can't I creat a object in Fraction?

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
Huglight
  • 35
  • 3
  • 4
    I think the error message is hiding the code with the error. Can you copy in the code that causes the error? – Jonathan Lam Apr 26 '18 at 04:18
  • You can't pass scanner object method x.nextInt() as an argument. You can do it with two way. 1:- int t = x.nextInt(); int y= x.nextInt(); Fraction f = new Fraction(t,y); 2:- You can pass scanner object as an argument along with change the implementation of the Fraction(Scanner x). – Dhiral Kaniya Apr 26 '18 at 04:22
  • Message from IDE is clear enough what mistake OP is doing. – Himanshu Bhardwaj Apr 26 '18 at 04:22
  • 1
    Welcome to Stack Overflow! [Please don't post your code as an image.](//meta.stackoverflow.com/q/285551) – 4castle Apr 26 '18 at 04:25
  • @DhiralKaniya OP's method works just fine. – TNT Apr 26 '18 at 04:31
  • Thank you all!The error message is similar to the next line, sorry about that – Huglight Apr 26 '18 at 05:08

1 Answers1

0

Fraction is defined as inner non-static class inside Main class. Hence to instantiate an object of Fraction you would first need to define an object of Main. And using that define an object of Fraction.

e.g.

Main m = new Main();
Fraction a = m.new Fraction(in.nextInt(), in.nextInt());

Or the other option you have is to define Fraction class as static.

e.g.

static class Fraction {
 ... and you class definition...
}

The right option depends on your usage entirely. But as per the sample you pasted option #2 defining the class as static would suit you more.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36