Writing a class with a main(使用mian的编写class)

1.所有的程序都是在一个class里,即使你在.Java的扩展名的文件下输入代码,实际上运行的是.class拓展名里的程序内容

2.而一整个class的运行是从main开始

 

What can you say in the main method?(你可以在main method里说些什么)

语句:声明、赋值、调用

循环:for和while循环

条件:if else

 

Looping(循环)

Java有三个循环结构:while、do-while和for

我们可以用一个简单的布尔测试(boolean tests)来验证我们的循环是否能正常运转

其中有两个问题

1.Q: 在我的另一种语言中,我可以对整数进行布尔测试。在Java中,我可以这样说:

int x=1;

while(x){}

A: 否。布尔值和整数在Java中是不兼容的类型。由于条件测试的结果必须是布尔值,因此可以直接测试的唯一变量(无需使用比较运算符)是布尔值。例如,您可以说:

boolean isHot = true;

while(isHot) { }

我理解的布尔测试是“我们可以用一个简单的布尔测试(boolean tests)来验证我们的循环是否能正常运转”但是上面这样一个操作又好像不是为了仅仅测试布尔值

 

2.既然一个“=”赋值运算符,用于赋值,那equals operator(等于运算符==)的作用是什么样的

这个问题在后面可以看到是为了验证值

 

head first java勘误 head in java_Java

 

我们可以很容易读懂上面这串代码的主要内容,即输入一个int值1后进入一个while循环,书中解释到一个布尔测试的内容在while(X<4) {......}  中的花括号内,那说明了布尔测试其实就是一个循环,并且输出的值便是它产生的布尔值

System.out.print  vs  System.out.println之间的区别

在运行程序输出结果时,System.out.print可以将输出的内容打印在同一行,而System.out.println输出的内容是可以换行到下一行输出

 

 

Conditional branching(条件分支)

if测试和while循环中的布尔测试基本相同

1 class IfTest {
2  public static void main (String[] args) {
3  int x = 3;
4  if (x == 3) {
5  System.out.println(“x must be 3”);
6  }
7  System.out.println(“This runs no matter what”);
8  }
9 }
1 class IfTest2 {
 2  public static void main (String[] args) {
 3  int x = 2;
 4  if (x == 3) {
 5  System.out.println(“x must be 3”);
 6  } else {
 7  System.out.println(“x is NOT 3”);
 8  }
 9  System.out.println(“This runs no matter what”);
10  }
11 }

 

在书中的实例1中可以看到,输入x=3,当x为3时,if判定3为真,如果结果为真,则输出“X must be 3”,如果结果为假则输出“this runs no matter what”

在书中的实例2中可以看到,输入x=2,当x为3时,if判定3为真,如果结果为真,则输出“X must be 3”,如果结果为假则输出“x is not 3”&“this runs no matter what”

那么我们可以很容易做出书旁边的这个作业

public class DooBee {
 public static void main (String[] args) {
 int x = 1;
 while (x < _____ ) {
 System.out._________(“Doo”);
 System.out._________(“Bee”);
 x = x + 1;
 }
 if (x == ______ ) {
 System.out.print(“Do”);
 }
 }
}

如果要得出以下的答案

Given the output:
% java DooBee
DooBeeDooBeeDo

那么我们只需要循环两次Doo和Bee以及循环一次Do

public class DooBee {
 public static void main (String[] args) {
 int x = 1;
 while (x < 3) {
 System.out.print(“Doo”);
 System.out.print(“Bee”);
 x = x + 1;
 }
 if (x == 3 ) {
 System.out.print(“Do”);
 }
 }
}