回想大学的三年有些浑浑噩噩,如今大四了!也该醒醒了!想把之前学的东西重新复习一遍。把本书的习题做一遍!
练习1:(1)使用“简短的”和正常的打印语句来编写一个程序。
答:所谓简短的即使用javaSE5中的新增加的概念静态导入
import static java.lang.System.out;
public class Test3_1{
public static void main(String[] args){
out.println("简短的输出!");
System.out.println("标准的输出!");
}
}
练习2:(1)创建一个包含一个float域的类,并用这个类来展示别名机制。
答:所谓的别名机制不过是将一个引用赋给另一个引用。是两个引用指向同一内存区域。这是我理解的别名机制,不知道对不对,希望大家给点意见。
public class Test3_2{
public static void main(String[] args){
Leaf l1 = new Leaf();
Leaf l2 = new Leaf();
l1.f = 10;
l2.f = 20;
l1 = l2;
System.out.println(l1.f);
System.out.println(l2.f);
}
}
class Leaf{
float f;
}
练习3:(1)创建一个包含一个float域的类,并用这个类来展示别名机制。
public class Test3_3{
static void g(Leaf l){
l.f = 30.0f;
}
public static void main(String[] args){
Leaf l1 = new Leaf();
l1.f = 10.0f;
System.out.println(l1.f);
g(l1);
System.out.println(l1.f);
}
}
class Leaf{
float f;
}
练习4:(2)编写一个计算速度的程序,它是同的距离和时间都是常量。
这题我没理解作者的用意!
当你在创建Random对象是给定一个参数也就是给定这个类一个种子那他生成的随机数列就是个定值。如果没有传递任何参数那么java就会将当前时间作为随机数生成器的种子。
import java.util.*;
public class Test3_4{
public static void main(String[] args){
double v,s,t;
Random rand = new Random(47);
s = rand.nextDouble();
t = rand.nextDouble();
v = s/t;
System.out.println("距离为:"+s);
System.out.println("时间为:"+t);
System.out.println("速度为:"+v);
}
}
练习5:(2)创建一个名为Dog的类,它包含两个String域;name和says。在main()方法中创建两个Dog对象,一个名为spot(它的叫声为“Ruff!”)另一个名为scruffy (它的叫声为“wurf!”)。然后显示他们的名字和叫声。
class Dog{
String name;
String says;
public static void main(String[] args){
Dog dog1 = new Dog();
dog1.says="spot";
dog1.name="Ruff";
Dog dog2 = new Dog();
dog2 .name="scruffy";
dog2 .says="Wurf";
System.out.println("Dog1的名为:"+dog1.name+"叫声是"+dog1.says);
System.out.println("Dog2的名为:"+dog2.name+"叫声是"+dog2.says);
}
}
练习6(3)在练习5的基础上,创建一个新的索引,并对其赋值为spot对象。测试用==和equals()方法来比较所有引用的结果。
答:不知道我理没理解对作者的意识 希望大家点评下。
class Dog{
String name;
String says;
public static void main(String[] args){
Dog dog1 = new Dog();
dog1.says="spot";
dog1.name="Ruff";
Dog dog2 = new Dog();
dog2 .name="scruffy";
dog2 .says="Wurf";
Dog dog3 = new Dog();
dog3 = dog1;
System.out.print("dog1与dog3的比较用==的");
System.out.println(dog3 == dog1);
System.out.print("dog1与dog3的比较用equals()方法的");
System.out.println(dog1.equals(dog3));
System.out.print("dog2与dog3的比较用==的");
System.out.println(dog2 == dog3);
System.out.print("dog2与dog3的比较用equals()方法的");
System.out.println(dog2.equals(dog3));
System.out.print("dog1与dog2的比较用==的");
System.out.println(dog1 == dog2);
System.out.print("dog1与dog2的比较用equals()方法的");
System.out.println(dog1.equals(dog2));
}
}
练习7:(3)编写一个程序模拟扔硬币的结果。
答:我没明白这题跟这章的内容有什么练习!可能是我使用的方式不对?
import java.util.*;
public class Test3_7{
public static void main(String[] args){
Random rand = new Random();
int i = rand.nextInt(100);
if(i%2==0){
System.out.println("你扔的是正面");
}else{
System.out.println("你扔的是背面");
}
}
}