scala-Sixth Chapter-rational

Source: Internet
Author: User

The knowledge points involved:
Check for prerequisites.

function overloading.

Operator overloading.

Console input.

Private functions.

An implicit conversion.


<pre name= "code" class= "java" >import java.io.bufferedreader;import Java.io.file;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.PrintStream; Import Java.io.printwriter;import Java.math.bigdecimal;class Rational (N:int, D:int) {require (d! = 0);//Check Prerequisites private  Val g = gcd (N.abs, d.abs);  Val num:int = n/g;    Val den:int = d/g;    Override Def toString = n + "/" + d;//overload tosting def this (n:int) = This (n, 1); def + (that:rational): rational =//define operation symbol new Rational (num * that.den + that.num * den, den * that.den) de F * (that:rational): rational = new rational (num * that.num, den * that.den) def * (i:int): rational =//reload * New Ra tional (I*num, den) def lessthan (that:rational) = This.num * That.den < That.num * This.den def max (that:ratio NAL) = if (This.lessthan (that)) so else this private def gcd (N:int, d:int): Int =//Private Function if (d==0) n Else gcd (d, n% d)}object Rational {def maiN (args:array[string]) {var bf = new BufferedReader (new InputStreamReader (system.in));    var line = Bf.readline ();    var eles = Line.split ("") val R1 = new Rational (integer.parseint (eles (0)), Integer.parseint (Eles (1)));    line = Bf.readline ();    Eles = Line.split ("");    Val R2 = new Rational (integer.parseint (eles (0)), Integer.parseint (Eles (1)));    Val R3 = R1 + R2;    Val R4 = new Rational (2);    Implicit def inttorational (x:int) = new Rational (x)//implicit conversion//implicit conversion to be placed in scope, not within class!    Val R5 = 2 * R3;  println (R5); }}




scala-Sixth Chapter-rational

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.