java实验报告

g.setColor(Color.RED); g.drawString(i+\ posX=posX+35; if(count%5==0){ posY=posY+20; posX=0; } } } } }

3) 在Applet画面中绘制一个19×19的围棋棋盘。棋盘的颜色由白(white)、灰(gray)、橘黄(orange)、浅红(pink)几种颜色中随机选取。 import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;

import javax.swing.JApplet;

public class chess extends Applet { public void paint(Graphics g) { int row=0; int col=0; int x, y; int sign; for (row = 0; row < 19; row++) { for (col = 0; col < 19; col++) { x = col * 20; y = row * 20; do { sign = (int) (Math.random() * 4); } while (sign == 4); if (sign == 0) g.setColor(Color.white); if (sign == 1) g.setColor(Color.gray); if (sign == 2) g.setColor(Color.orange); if (sign == 3) g.setColor(Color.pink); g.fillRect(x, y, 20, 20); } }

} }

二、提高题

1)绘制数学函数y=sin(x)的曲线(其中,x的取值为0~360)。 import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;

public class sinX extends Applet { double x; double y; public void paint(Graphics g){ g.setColor(Color.RED); for(x=0;x<=360;x++){ y=Math.sin(x)*70+100; g.fillOval((int)x,(int)y,3,3); x=x+5; } } }

2)绘制一个太阳包括若干射线,让太阳在Applet画面上从左向右缓慢移动,到最右边由重新回到左边。

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;

public class sun extends Applet{ int circlex,circley; //太阳左上角坐标 int circleWidth,circleHeight; //射线端点坐标 int x1[]=new int[8]; int y1[]=new int[8]; int x2[]=new int[8]; int y2[]=new int[8]; int pos=0; public void init(){ System.out.println(getWidth()); circlex=30; circley=30;

}

circleWidth=70; circleHeight=70;

x1[0]=65; y1[0]=0; x2[0]=65; y2[0]=20;

x1[1]=100; y1[1]=30; x2[1]=115; y2[1]=15;

x1[2]=110; y1[2]=65; x2[2]=140; y2[2]=65;

x1[3]=100; y1[3]=100; x2[3]=115; y2[3]=115;

x1[4]=65; y1[4]=110; x2[4]=65; y2[4]=140;

x1[5]=30; y1[5]=100; x2[5]=15; y2[5]=115;

x1[6]=0; y1[6]=65; x2[6]=20; y2[6]=65;

x1[7]=30; y1[7]=30; x2[7]=15; y2[7]=15;

public void paint(Graphics g){ g.setColor(Color.GREEN); for(int i=0;i<8;i++){ g.drawLine(x1[i]+pos,y1[i],x2[i]+pos,y2[i]); } g.fillOval(circlex+pos,circley,circleWidth, circleHeight); try { Thread.sleep(100); } catch (InterruptedException e) {} pos++; if (pos+x2[2]>getWidth()) pos=0; repaint(); } }

3)从Applet参数获取一个字符串,统计其中每个英文字母出现的次数(不区分大小写)。 import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics;

public class letter extends Applet { String string=\ int count=0; public void init(){ string=\ } public void paint(Graphics g){ for(int i=0;i=65&&string.charAt(i)<=90)||(string.charAt(i)>=97&&string.charAt(i)<=122)) count++; } g.setColor(Color.magenta); Font font=new Font(\黑体\ g.setFont(font); g.drawString(\该字符串中共有英文字母\个\ } }

联系客服:779662525#qq.com(#替换为@)