标签:
1. 编写一个Conversions对象,加入inchesToCentimeters、gallonsToLiters和milesToKilometers方法。
object
Conversions {
def
main(args
:
Array[String]){
printf(
"1 inch = %g centimeters\n"
, inchesToCentimeters(
1
))
printf(
"2 gallons = %g liters\n"
, gallonsToLiters(
2
))
printf(
"3 miles = %g centimeters\n"
, milesToKilometers(
3
))
}
def
inchesToCentimeters(inches
:
Double)
=
{
inches *
2.54
}
def
gallonsToLiters(gallons
:
Double)
=
{
gallons *
3.7854118
}
def
milesToKilometers(miles
:
Double)
=
{
miles *
1.609344
}
}
/*result
1 inch = 2.54000 centimeters
2 gallons = 7.57082 liters
3 miles = 4.82803 centimeters
*/
abstract
class
UnitConversions{
def
convert(amt
:
Double)
:
Double
}
object
inchesToCentimeters
extends
UnitConversions{
override
def
convert(amt
:
Double)
=
amt *
2.54
}
object
gallonsToLiters
extends
UnitConversions{
override
def
convert(amt
:
Double)
=
amt *
3.7854118
}
object
milesToKilometers
extends
UnitConversions{
override
def
convert(amt
:
Double)
=
amt *
1.609344
}
printf(
"1 inch = %g centimeters\n"
, inchesToCentimeters.convert(
1
))
printf(
"2 gallons = %g liters\n"
, gallonsToLiters.convert(
2
))
printf(
"3 miles = %g centimeters\n"
, milesToKilometers.convert(
3
))
/*result
1 inch = 2.54000 centimeters
2 gallons = 7.57082 liters
3 miles = 4.82803 centimeters
*/
import
java.awt.
_
object
Origin
extends
Point{
override
def
getLocation
:
Point
=
super
.getLocation
}
Origin.move(
2
,
3
)
println(Origin.toString)
/*result
Main$$anon$1$Origin$[x=2,y=3]
*/
class
Point
private
(
val
x
:
Int,
val
y
:
Int){
override
def
toString
=
"Point at [x=%d,y=%d]"
.format(x,y)
}
object
Point{
def
apply(x
:
Int, y
:
Int)
=
new
Point(x,y)
}
val
a
=
Point(
3
,
4
)
println(a.toString)
/*result
Point at [x=3,y=4]
*/
object
Reverse{
def
main(args
:
Array[String]){
for
(i <- (
0
until args.length).reverse) print(args(i) +
" "
)
}
}
/* The following code did not work for me.
object Reverse extends App{
for(i <- (0 until args.length).reverse) print(args(i) + " ")
}
*/
/*result
World Hello
*/
object
Poker
extends
Enumeration
with
App{
val
Heart
=
Value(
3
,
"
♥"
)
val
Diamond
=
Value(
4
,
"
♦"
)
val
Club
=
Value(
5
,
"
♣"
)
val
Spade
=
Value(
6
,
"
♠"
)
println(Poker.Heart)
println(Poker.Diamond)
println(Poker.Club)
println(Poker.Spade)
}
object
Card
extends
Enumeration
with
App{
val
Heart
=
Value(
3
,
""
)
val
Diamond
=
Value(
4
,
""
)
val
Club
=
Value(
5
,
""
)
val
Spade
=
Value(
6
,
""
)
def
color(c
:
Card.Value){
if
(c
==
Card.Club || c
==
Card.Spade) print(
"Black"
)
else
print(
"Red"
)
}
color(Card.Heart)
}
/*
Red
*/
object
RGB
extends
Enumeration
with
App{
val
RED
=
Value(
0xff0000
,
"Red"
)
val
BLACk
=
Value(
0x000000
,
"Black"
)
val
GREEN
=
Value(
0x00ff00
,
"Green"
)
val
CYAN
=
Value(
0x00ffff
,
"Cyan"
)
val
YELLO
=
Value(
0xffff00
,
"Yellow"
)
val
WHITE
=
Value(
0xffffff
,
"White"
)
val
BLUE
=
Value(
0x0000ff
,
"Blue"
)
val
MAGENTA
=
Value(
0xff00ff
,
"Magenta"
)
}
标签:
原文地址:http://www.cnblogs.com/chenjo/p/4436595.html