所以请原谅任何非正式场合。
我已经使用半径和高度的扫描值成功计算了圆柱体的面积和体积,但现在想要构建一个applet,它给出圆柱体的图形表示,同时显示下面的值。
我已经做了一半:我已经构建了一个小程序,它绘制一个圆柱体并在其下面打印信息(使用drawOval,drawLine和drawString) - 但是varibles必须是常量。使用java Applet时我不能使用scanner.in。反正这个,我应该使用其他一些方法或库吗?
以下代码: -
import java.util.Scanner;
/**
* Draw a cylinder using radius and height; and calculate base, lateral and total area; and volume.
* vrsn 0.1 draw text data below cylinder
* @author (thkoby)
* @vrsn 0.1 dt. Jan 6, 2015
* @vrsn 0.0 dt. Jan. 5, 2015
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.applet.Applet;
import java.awt.*;
public class cyl extends Applet {
double Pi = 3.1415926; //global value for constant pi
public void paint (Graphics g) {
int bottX; //x pos. bottom cylinder
int bottY;
int topX; //x pos. top cylinder
int topY;
double bArea; //base area
double tArea; //total area
double lArea; //lateral area
double vol; //volume
double rad = 10; //radius
double height = 20; //height
int r = (int) rad;
int h = (int) height;
int d = 2*r; //diameter
int fontSize = 12;
bArea = baseArea(rad);
tArea = totalArea(rad,height);
lArea = lateralArea(rad,height);
vol = volume(rad,height);
//x,y pos. for bottom oval
bottX = 20;
bottY = 20 + h;
//x,y pos. for top oval
topX = 20;
topY = 20;
//Graphical representation of the cylinder
g.drawOval (topX, topY, d, r); //radius is used to give angled appearance
g.drawOval (bottX, bottY, d, r);
g.drawLine (topX,topY+(r/2),bottX,bottY+(r/2));
g.drawLine (topX+d,topY+(r/2),bottX+d,bottY+(r/2));
//text information below cylinder
g.setFont(new Font("Courier", Font.PLAIN, fontSize));
g.setColor(Color.black);
g.drawString("Radius: "+r, 20, 40+h+r);
g.drawString("Height: "+h, 20, 54+h+r);
g.drawString("Base Area: "+bArea, 20, 68+h+r);
g.drawString("Total Area: "+tArea, 20, 82+h+r);
g.drawString("Lateral Area: "+lArea, 20, 96+h+r);
g.drawString("Volume: "+vol, 20, 110+h+r);
}
public double baseArea(double rad) { //base area = radius squared * pi
return (rad*rad)*Pi;
}
public double totalArea(double rad,double height) { //total area = 2pi * radius * (height + radius)
return 2*Pi*rad*(height + rad);
}
public double lateralArea(double rad, double height) { //lateral area = 2pi * radius * height
return 2*Pi*rad*height;
}
double volume(double rad, double height) { //volume = 2pi * radius squared * height
return Pi*(rad*rad)*height;
}
}