代码改变世界

Java 学习笔记 (六) Java 定义变量

2018-01-12 15:30  钱先生  阅读(223)  评论(0编辑  收藏  举报

这个问题来自于head first一书page68.

 1 package com.idea.study;
 2 
 3 public class Books {   //headfirst page68
 4     String title;   //为什么要写在这里?写在方法里就不行?
 5     String author;
 6     public static void main(String[] args){
 7         Books[] myBooks = new Books[3];
 8         int x=0;
 9         myBooks[0] = new Books();
10         myBooks[1] = new Books();
11         myBooks[2] = new Books();
12         myBooks[0].title = "The Grapes of Java";
13         myBooks[1].title = "The Java Gatsby";
14         myBooks[2].title = "The Java Cookbook";
15         myBooks[0].author = "bob";
16         myBooks[1].author = "sue";
17         myBooks[2].author = "ian";
18         while(x<3){
19             System.out.print(myBooks[x].title);
20             System.out.print(" by ");
21             System.out.println(myBooks[x].author);
22             x=x+1;
23         }
24 
25 
26     }
27 }