@Sarah
2015-04-24T10:02:09.000000Z
字数 8318
阅读 1358
int size = 27;
//声明一个integer类型,名称为size的变量并初始值为27
String name = “Fido”;
//声明名声为name的字符串,值为fido
Dog myDog = new Dog(name, size);
////以name和size声明一个名称为mydog的dog变量
x=size-5;
//把size值减5的结果赋值给变量x
if (x < 15) myDog.bark(8);
//如果x<15让狗叫八次
while(x>3){
//当x>3 就持续执行循环
myDog.play();
}
//让狗执行play动作,{}里是循环内容
int[] numList = {2,4,6,8};
//声明有四个元素的整形数组
System.out.print(“Hello”);
System.out.print(“Dog: “ + name);
String num = “8”;
//声明字符串变量num并赋值为8
int z = Integer.parseInt(num);
//讲字符串8转换成整数8
try {
//尝试列出可能会引起异常状况的指令
readTheFile(“myFile.txt”);
}
//读取myfile.txt这个文件
catch(FileNotFoundException ex) {
//捕获万一发生找不到文件异常状况
System.out.print(“File not found.”);
//找不到就说找不到
//{}里面就是异常处理情况
//声明 设定 调用方法等语句
int x = 3;
String name = “Dirk”;
x = x * 17;
System.out.print(“x is ” + x);
double d = Math.random();
//反复做某事 while与for循环
while (x > 12) {
x = x -1;
}
for (int x = 0; x < 10; x = x + 1) {
System.out.print(“x is now ” + x);
}
//在适当条件下做某事 if/else条件分支
if (x == 10) {
System.out.print(“x must be 10”);
} else {
System.out.print(“x isn’t 10”);
}
if ((x < 3) & (name.equals(“Dirk”))) {
System.out.println(“Gently”);
}
System.out.print(“this line runs no matter what”);
//while循环范例
public class Loopy {
public static void main (String[] args) {
int x = 1;
System.out.println(“Before the Loop”);
while (x < 4) {
System.out.println(“In the loop”);
System.out.println(“Value of x is ” + x);
x = x + 1;
}
System.out.println(“This is after the loop”);
}
}
//if/else范例
class IfTest2 {
public static void main (String[] args) {
int x = 2;
if (x == 3) {
System.out.println(“x must be 3”);
} else {
System.out.println(“x is NOT 3”);
}
System.out.println(“This runs no matter what”);
}
}
//从99数到0
public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = “bottles”;
while (beerNum > 0) {
if (beerNum == 1) {
word = “bottle”; // 单数的瓶子
}
System.out.println(beerNum + “ ” + word + “ of beer on the wall”);
System.out.println(beerNum + “ ” + word + “ of beer.”);
System.out.println(“Take one down.”);
System.out.println(“Pass it around.”);
beerNum = beerNum - 1;
if (beerNum > 0) {
System.out.println(beerNum + “ ” + word + “ of beer on the wall”);
} else {
System.out.println(“No more bottles of beer on the wall”);
}//else循环结束
} //while循环结束
} //main方法结束
} //class结束
要点
*语句以分号结束
*程序块以{}划出范围
*用名称与类型声明变量
*等号是赋值运算符
*两个等号用来当等式
*只要是真,while会一直执行块内的程序
*把bollean测试放在括号中
形象化对象
*对象本身已知的事物称为实例变量
*类是对象的蓝图
创建对象
创建与测试movie对象实现
class Movie {
String title;
String genre;
int rating;
void playIt() {
System.out.println(“Playing the movie”);
}
}
public class MovieTestDrive {
public static void main(String[] args) {
Movie one = new Movie();
one.title = “Gone with the Stock”;
one.genre = “Tragic”;
one.rating = -2;
Movie two = new Movie();
two.title = “Lost in Cubicle Space”;
two.genre = “Comedy”;
two.rating = 5;
two.playIt();
Movie three = new Movie();
three.title = “Byte Club”;
three.genre = “Tragic but ultimately uplifting”;
three.rating = 127;
}
}
main()的真正用途
*测试真正的类
*启动你的JAVA应用程序
猜数字游戏
代码实现
public class GuessGame {
Player p1;
Player p2;
Player p3;
//用3个实例变量表示三个player对象
public void startGame() {
p1 = new Player();
p2 = new Player();
p3 = new Player();
//创建出player对象
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
//声明三个变量来保存是否猜中
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
//声明三个变量来保存猜测的数字
int targetNumber = (int) (Math.random() * 10);
System.out.println(“I’m thinking of a number between 0 and 9...”);
//产生谜底数字
while(true) {
System.out.println(“Number to guess is “ + targetNumber);
p1.guess();
p2.guess();
p3.guess();
//调用player的guess()方法
guessp1 = p1.number;
System.out.println(“Player one guessed “ + guessp1);
guessp2 = p2.number;
System.out.println(“Player two guessed “ + guessp2);
guessp3 = p3.number;
System.out.println(“Player three guessed “ + guessp3);
//取得每个player猜测的数字并列出
if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
//检查是否猜中,若猜中则去设定是否猜中的变量
if (p1isRight || p2isRight || p3isRight) {
//如果有一个或多个猜中
System.out.println(“We have a winner!”); System.out.println(“Player one got it right? “ + p1isRight);
System.out.println(“Player two got it right? “ + p2isRight);
System.out.println(“Player three got it right? “ + p3isRight);
System.out.println(“Game is over.”);
break; //游戏结束终止循环
} else {
// 都没猜到所以要继续下去
System.out.println(“Players will have to try again.”);
} // if/else结束
} // 循环结束
} // 方法结束
} // 类结束
运行猜数字游戏
public class Player {
int number = 0; // 要被猜的数字
public void guess() {
number = (int) (Math.random() * 10);
System.out.println(“I’m guessing “+ number);
}
}
public class GameLauncher {
public static void main (String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
变量有两种
主数据类型
引用
声明变量:变量必须有类型和名称。
名称要避开保留字
圆点运算符
取得圆点前面的对象,然后求出该对象在圆点后面的事物
myDog.bark();
//名为mydog的变量引用对象上的bark()
int myDog = new Dog();
//对象的声明 创建 与赋值
引用范例
class Dog {
String name;
public static void main (String[] args) {
// 创建dog对象
Dog dog1 = new Dog();
dog1.bark();
dog1.name = “Bart”;
//创建dog数组
Dog[] myDogs = new Dog[3];
// 关门放狗
myDogs[0] = new Dog();
myDogs[1] = new Dog();
myDogs[2] = dog1;
// 通过数据引用存取Dog
myDogs[0].name = “Fred”;
myDogs[1].name = “Marge”;
// myDog[2]的名字
System.out.print(“last dog’s name is “);
System.out.println(myDogs[2].name);
// 逐个对Dog执行bark()
int x = 0;
while(x < myDogs.length) {
//数组有个length变量能够返回元素的数目
myDogs[x].bark();
x = x + 1;
}
}
public void bark() {
System.out.println(name + “ says Ruff!”);
}
public void eat() { }
public void chaseCat() { }
}
要点
变量的声明必须有类型和名称
引用变量的值代表位于堆之对象的存取方法
引用变量如同遥控器,对引用变量使用圆点运算符可以如同按下遥控器按钮般的存取它的方法或者实例变量
数组一定是一个对象
Dog d = new Dog();
d.bark(3);
//调用dog上的bark()方法,并传入3这个值作为此方法的参数
//以int类型表示的值3会传递给bark()
void bark (int numOfBarks) {
//此值会传给numofbarks这个参数(int类型的变量)
while (numOfBarks>0){
system.out.printlin(“ruff”);
numOfBarks=numOfBarks-1;
//把numOfBarks当作一般的变量使用
}
}
class Dog {
int size;
String name;
void bark() {
if (size > 60) {
System.out.println(“Wooof! Wooof!”);
} else if (size > 14) {
System.out.println(“Ruff! Ruff!”);
} else {
System.out.println(“Yip! Yip!”);
}
}
}
class DogTestDrive {
public static void main (String[] args){
Dog one = new Dog();
one.size = 70;
Dog two = new Dog();
two.size = 8;
Dog three = new Dog();
three.size = 35;
one.bark();
two.bark();
three.bark();
}
}
A method uses parameters. A caller passes arguments.
You can send more than one thing to a method
void go() {
TestStuff t = new TestStuff();
t.takeTwo(12, 34);
}
void takeTwo(int x, int y) {
int z = x + y;
System.out.println(“Total is ” + z);
}
//Calling a two-parameter method, and sending it two arguments.
void go() {
int foo = 7;
int bar = 3; t.takeTwo(foo, bar);
}
void takeTwo(int x, int y) {
int z = x + y;
System.out.println(“Total is ” + z);
}
//You can pass variables into a method, as long as the variable type matches the parameter type.
int x = 7;
/*Declare an int variable and assign it the value ‘7’. The bit pattern for 7 goes into the variable named x.*/
void go(int z){ }
//Declare a method with an int parameter named z.
foo.go(x);
void go(int z){ }
/*Call the go() method, passing the variable x as the argument. The bits in x are copied, and the copy lands in z.*/
void go(int z){ z = 0;
}
/*Change the value of z inside the method. The value of x doesn’t change! The argument passed to the z parameter was only a copy of x.
The method can’t change the bits that were in the calling variable x.*/
class ElectricGuitar {
String brand;
int numOfPickups; boolean rockStarUsesIt;
String getBrand() { return brand;
}
void setBrand(String aBrand) { brand = aBrand;
}
int getNumOfPickups() { return numOfPickups;
}
void setNumOfPickups(int num) { numOfPickups = num;
}
boolean getRockStarUsesIt() { return rockStarUsesIt;
}
void setRockStarUsesIt(boolean yesOrNo) { rockStarUsesIt = yesOrNo;
}
}
Encapsulating the GoodDog class
class GoodDog {
private int size;
//Make the instance variable private.
public int getSize() {
return size;
}
public void setSize(int s) {
//Make the getter and setter methods public.
size = s;
}
void bark() {
if (size > 60) {
System.out.println(“Wooof! Wooof!”);
} else if (size > 14) {
System.out.println(“Ruff! Ruff!”);
} else {
System.out.println(“Yip! Yip!”);
}
}
}
class GoodDogTestDrive {
public static void main (String[] args) {
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System.out.println(“Dog one: “ + one.getSize()); System.out.println(“Dog two: “ + two.getSize()); one.bark();
two.bark();
}
}
//Even though the methods don’t really add new functionality, the cool thing is that you can change your mind later. you can come back and make a method safer, faster, better.
How do objects in an array behave?
Dog[] pets;
pets = new Dog[7];
//Declare and create a Dog array, to hold 7 Dog references.
pets[0] = new Dog();
pets[1] = new Dog();
//Create two new Dog objects, and assign them to the first two array elements.
pets[0].setSize(30);
int x = pets[0].getSize();
pets[1].setSize(8);
//Call methods on the two Dog objects.
The difference between instance and local variables
Instance variables are declared inside a class but not within a method.
class Horse {
private double height = 15.2;
private String breed;
// more code...
}
Local variables are declared within a method.
class AddThing {
int a;
int b = 12;
public int add() {
int total = a + b;
return total;
}
}
Local variables MUST be initialized before use!
To compare two primitives, use the == operator
int a = 3;
byte b = 3;
if (a == b) { // true }
To see if two references are the same (which means they refer to the same object on the heap) use the == operator
Foo a = new Foo();
Foo b = new Foo();
Foo c = a;
if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }