一、猜数游戏改进
昨天写的猜数游戏的程序和书上的答案相比还有一些不足:
- 程序main()方法中的内容太多,没有集成到类里面。
- 类名应该以大写字母开头。
- 若一轮游戏中,三位玩家都没猜中,需要开始新一轮游戏。
修改后的代码如下:
class GameLauncher
{
public static void main(String[] args)
{
GuessGame game = new GuessGame();
game.startGame();
}
}
class Player
{
int gusnum = (int)(Math.random() * 10);
}
class GuessGame
{
void startGame()
{
boolean wins = false;
while(true)
{
int truenum = (int)(Math.random() * 10);
for(int i=0; i<3; i++)
{
Player plr = new Player();
int gusnum = plr.gusnum;
if(gusnum == truenum)
{
System.out.printf("Player %d gueses right.\n", i+1);
wins = true;
}
else
{
System.out.printf("Player %d gueses wrong. The guess number is: %d\n", i+1, gusnum);
}
}
System.out.printf("The right number is: %d\n", truenum);
if(wins)
{
System.out.println("We have a winner/winners!");
break;
}
else
{
System.out.println("No one's right. Let's do it again.\n");
}
}
}
}
程序输出结果:
二、认识变量
变量有两种:primitive主数据类型和引用。主数据类型用来保存基本类型的值,包括整型、布尔型和浮点型等;而对象引用保存的是对对象的引用。
声明变量
- 要使用变量必须先声明变量。声明的时候必须要指明变量类型和变量名称。
- 主数据类型除了变量类型,还有大小。比如整型变量有long、int、short、byte四种大小,分别为64、32、16、8位;浮点型变量double和float两种大小,分别为64、32位;字符型为16位。主数据类型的声明和赋值示例:
int x = 234;
float f = 32.5f;
只有加上f,数值才会被当作float类型,否则所有带有小数点的值都会被java当作double类型。
如果把较大类型的变量值赋给较小类型的变量,那么编译器会报错,比如下面的语句是不可以的:
int x = 24;
byte b = x;
- 实际上,没有“对象变量”这样的东西存在,只有引用到对象的变量。引用变量保存的是存取对象的方法,它类似于指向对象的指针。通过圆点"."来存取对象的变量和方法。对于同一个虚拟机来说,所有的引用大小都一样。不过,不同于C语言,
java不能对引用变量进行运算
(比如p++;是不行的)。
变量命名规则
- 必须以字母、下划线或"$"开头,不能用数字开头。
- 必须避开java保留字。
- Java保留字:abstract、assert、boolean、break、byte、case、catch、char、class、continue、default、do、double、else、enum、extends、final、finally、float、for、if、implements、import、int、interface、instanceof、long、native、new、package、private、protected、public、return、short、static、strictfp、super、switch、synchronized、this、throw、throws、transient、try、void、volatile、while、goto、const、true、false、null。
数组的创建
- 声明:
变量类型后面加个[],可以声明数组变量:
int[] nums;
- 创建对象和赋值:
new方法要求虚拟机分配堆空间给新建立的对象。下面是创建了一个大小为7的int型数组,并将它赋给nums(这里的int实际上也算是一个类,对于自定义类也可以这么操作):
nums = new int[7];
- 对数组每个元素赋值:
nums[0]=1;nums[1]=29;...
注意int数组中每个元素的类型都是int。
自定义类的数组创建
Dog[] pets; //声明一个Dog类型的数组pets
pets = new Dog[2]; //分配内存,赋值给pets数组
pets[0] = new Dog();
pets[1] = new Dog(); //给数组pets的每一个元素创建赋值一个Dog对象
pets[0].name = "Fido"; //给pest[0]对象的实例变量name赋值
pets[0].bark(); //调用pets[0]对象的bark()方法