跟着王洋老师学编程 - 1.3 满天星星

发布时间 2023-12-06 16:54:33作者: Shannon_Zhang

编写程序,以窗体形式实现“满天星星”

代码一

 1 import java.awt.Frame;
 2 import java.awt.Color;
 3 import java.awt.Panel;
 4 import java.awt.Graphics;
 5 public class StarSky{
 6     public static void main(String[] args){
 7         Frame w = new Frame();
 8         w.setSize(1366,768);
 9         w.setBackground(Color.BLACK);
10         // 
11         MyStarPanel msp = new MyStarPanel();
12         w.add(msp);
13         w.show();
14     }
15 }
16 class MyStarPanel extends Panel{
17     public void paint(Graphics g){
18         g.setColor(Color.white);
19         int i=30, j=30, k=0;
20         for(;k<1000;k++){
21             g.drawString("*",i,j);
22             i=(int)Math.random()*1366;
23             j=(int)Math.random()*768;
24             //i++;j++;
25             System.out.println(i,j);    
26         }
27         
28     }
29 }

 

编译报错如下

【解决方案】

查询菜鸟教程中JAVA流的用法得知System.out.println()参数只能是一个(字符串),如果要多个,需要加+连接符:

https://m.runoob.com/java/java-files-io.html

 

所以,调整代码如下↓↓↓

代码二

 1 import java.awt.Frame;
 2 import java.awt.Color;
 3 import java.awt.Panel;
 4 import java.awt.Graphics;
 5 public class StarSky{
 6     public static void main(String[] args){
 7         Frame w = new Frame();
 8         w.setSize(1366,768);
 9         w.setBackground(Color.BLACK);
10         // 添加画布
11         MyStarPanel msp = new MyStarPanel();
12         w.add(msp);
13         w.show();
14     }
15 }
16 class MyStarPanel extends Panel{
17     public void paint(Graphics g){
18         g.setColor(Color.white);
19         int i=30, j=30, k=0;
20         for(;k<1000;k++){
21             g.drawString("*",i,j);
22             i=(int)Math.random()*1366;
23             j=(int)Math.random()*768;
24             //i++;j++;
25             System.out.println(i);    
26             System.out.println(j);
27         }
28         
29     }
30 }

 

编译后,执行,打印的i,j 都是0……

【解决方案】

检查原书中代码,发现i,j 的强制转换,(int)后面的内容也是包在()里的…………调整代码如下。。

 1 import java.awt.Frame;
 2 import java.awt.Color;
 3 import java.awt.Panel;
 4 import java.awt.Graphics;
 5 public class StarSky{
 6     public static void main(String[] args){
 7         Frame w = new Frame();
 8         w.setSize(1366,768);
 9         w.setBackground(Color.BLACK);
10         // 
11         MyStarPanel msp = new MyStarPanel();
12         w.add(msp);
13         w.show();
14     }
15 }
16 class MyStarPanel extends Panel{
17     public void paint(Graphics g){
18         g.setColor(Color.white);
19         int i=30, j=30, k=0;
20         for(;k<1000;k++){
21             g.drawString("*",i,j);
22             i=(int)(Math.random()*1366);
23             j=(int)(Math.random()*768);
24             System.out.println(i);    
25             System.out.println(j);
26         }
27         
28     }
29 }

执行结果如下: