共有5個檔案,可以玩看看

編譯:
javac DataWin.java DemoStat.java Graphs.java StatApplet.java Stats.java StatsWin.java

執行:
javaw DemoStat

DataWin
-------------------------------------------------
import java.awt.event.*;
import java.awt.*;

// Display an array of numeric data.
class DataWin extends Frame {
TextArea dataTA;

DataWin(double[] data) {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setVisible(false);
dispose();
}
});

dataTA = new TextArea(10, 10);
dataTA.setEditable(false);

for(int i=0; i < data.length; i++)
dataTA.append(data[i]+"\n");

setSize(new Dimension(100, 140));
setLocation(320, 100);

setTitle("Data");
setResizable(false);

add(dataTA);

setVisible(true);
}
}


-------------------------------------------------
DemoStat
-------------------------------------------------
// Demonstrate the Stats and Graphs.
import java.io.*;
import java.awt.*;

class DemoStat {
public static void main(String args[])
throws IOException
{
double nums[] = { 10, 10, 11, 9, 8, 8, 9,
10, 10, 13, 11, 11, 11,
11, 12, 13, 14, 16, 17,
15, 15, 16, 14, 16 };

new StatsWin(nums);
}
}


-------------------------------------------------
Graphs
-------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

// A general-purpose graph class.
public class Graphs extends Frame {
// Constants for type of graph.
public final static int BAR = 0;
public final static int SCATTER = 1;
public final static int REGPLOT = 2;

private int graphStyle;

/* These specify the amount of space to
leave between data and borders. */
private final int leftGap = 2;
private final int topGap = 2;
private final int bottomGap = 2;
private int rightGap; // this value is computed

// These hold the min and max values of the data.
private double min, max;

// Refers to the data.
private double[] data;

// Colors used by the graph.
Color gridColor = new Color(0, 150, 150);
Color dataColor = new Color(0, 0, 0);

// Various values used to scale and display data.
private int hGap; // space between data points
private int spread; // distance between min and max data
private double scale; // scaling factor
private int baseline; // vertical coordinate of baseline

// Location of data area within the window.
private int top, bottom, left, right;

public Graphs(double[] vals, int style) {
// Handle window-closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setVisible(false);
dispose();
}
});

// Handle resize events.
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
repaint();
}
});

graphStyle = style;

data = vals;

// Sort the data to find min and max values.
double t[] = new double[vals.length];
System.arraycopy(vals, 0, t, 0, vals.length);
Arrays.sort(t);
min = t[0];
max = t[t.length-1];

setSize(new Dimension(200, 120));

switch(graphStyle) {
case BAR:
setTitle("Bar Graph");
setLocation(25, 250);
break;
case SCATTER:
setTitle("Scatter Graph");
setLocation(250, 250);
break;
case REGPLOT:
setTitle("Regression Plot");
setLocation(475, 250);
break;
}

setVisible(true);
}

public void paint(Graphics g) {

Dimension winSize = getSize(); // size of window
Insets ins = getInsets(); // size of borders

// Get the size of the curently selected font.
FontMetrics fm = g.getFontMetrics();

// Compute right gap.
rightGap = fm.stringWidth("" + data.length);

// Compute the total insets for the data region.
left = ins.left + leftGap + fm.charWidth('0');
top = ins.top + topGap + fm.getAscent();
bottom = ins.bottom + bottomGap + fm.getAscent();
right = ins.right + rightGap;

/* If minimum value positive, then use 0
as the starting point for the graph.
if maximum value is negative, use 0. */
if(min > 0) min = 0;
if(max < 0) max = 0;

/* Compute the distance between the minimum
and maximum values. */
spread = (int) (max - min);

// Compute the scaling factor.
scale = (double) (winSize.height - bottom - top) / spread;

// Find where the baseline goes.
baseline = (int) (winSize.height - bottom + min * scale);

// Compute the spacing between data.
hGap = (winSize.width - left - right) / (data.length-1);

// Set the grid color.
g.setColor(gridColor);

// Draw the baseline.
g.drawLine(left, baseline,
left + (data.length-1) * hGap, baseline);

// Draw the Y axis.
if(graphStyle != BAR)
g.drawLine(left, winSize.height-bottom, left, top);

// Display the min, max, and 0 values.
g.drawString("0", ins.left, baseline+fm.getAscent()/2);

if(max != 0)
g.drawString("" + max, ins.left, baseline -
(int) (max*scale) - 4);
if(min != 0)
g.drawString("" + min, ins.left, baseline -
(int) (min*scale)+fm.getAscent());

// Display number of values.
g.drawString("" + data.length,
(data.length-1) * (hGap) + left,
baseline + fm.getAscent());

// Set the data color.
g.setColor(dataColor);

// Display the data.
switch(graphStyle) {
case BAR:
bargraph(g);
break;
case SCATTER:
scatter(g);
break;
case REGPLOT:
regplot(g);
break;
}
}

// Display a bar graph.
private void bargraph(Graphics g) {
int v;

for(int i=0; i < data.length; i++) {
v = (int) (data[i] * scale);

g.drawLine(i*hGap+left, baseline,
i*hGap+left, baseline - v);
}
}

// Display a scatter graph.
private void scatter(Graphics g) {
int v;

for(int i=0; i < data.length; i++) {
v = (int) (data[i] * scale);
g.drawRect(i*hGap+left, baseline - v, 1, 1);
}
}

// Display a scatter graph with regression line.
private void regplot(Graphics g) {
int v;

RegData rd = Stats.regress(data);

for(int i=0; i < data.length; i++) {
v = (int) (data[i] * scale);
g.drawRect(i*hGap+left, baseline - v, 1, 1);
}

// Draw the regression line.
g.drawLine(left, baseline - (int) ((rd.a)*scale),
hGap*(data.length-1)+left+1,
baseline - (int) ((rd.a+(rd.b*(data.length-1)))*scale));
}
}


-------------------------------------------------
StatApplet
-------------------------------------------------
// An demonstration applet that uses Stats and Graphs.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
/*



*/

public class StatApplet extends Applet implements ActionListener {
StatsWin sw;
Button show;

ArrayList al = new ArrayList();

public void init() {
StringTokenizer st = new
StringTokenizer(getParameter("data"), ", \n\r");

String v;

// Get the values from the HTML.
while(st.hasMoreTokens()) {
v = st.nextToken();
al.add(v);
}

show = new Button("Display Statistics");
add(show);

show.addActionListener(this);
}

public void actionPerformed(ActionEvent ae) {

if(sw == null) {
double nums[] = new double[al.size()];
try {
for(int i=0; i nums[i] = Double.parseDouble((String)al.get(i));
} catch(NumberFormatException exc) {
System.out.println("Error reading data.");
return;
}

sw = new StatsWin(nums);
show.setEnabled(false);

sw.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
sw = null;
show.setEnabled(true);
}
});
}
}
}


-------------------------------------------------
Stats
-------------------------------------------------
import java.util.*;
import java.text.*;

// This class holds the regression analysis data.
class RegData {
public double a, b;
public double cor;
public String equation;

public RegData(double i, double j, double k, String str) {
a = i;
b = j;
cor = k;
equation = str;
}
}

// This is the exception thrown by Mode()
class NoModeException extends Exception {
public String toString() {
return "Set contains no mode.";
}
}

// A general-purpose statistics class.
public class Stats {
// Return the average of a set of values.
public static double mean(double[] vals) {
double avg = 0.0;

for(int i=0; i < vals.length; i++)
avg += vals[i];

avg /= vals.length;

return avg;
}

// Return the median of a set of values.
public static double median(double[] vals) {
double temp[] = new double[vals.length];

System.arraycopy(vals, 0, temp, 0, vals.length);

Arrays.sort(temp); // sort the data

// Return the middle value.
if((vals.length)%2==0) {
// If even number of values, find average
return (temp[temp.length/2] +
temp[(temp.length/2)-1]) /2;
} else return
temp[temp.length/2];
}

/* Returns the mode of a set of values.
A NoModeException is thrown if no value
occurs more frequently than any other.
If two or more values occur with the
same frequency, the first value is
returned. */
public static double mode(double[] vals)
throws NoModeException
{
double m, modeVal = 0.0;
int count, oldcount = 0;

for(int i=0; i < vals.length; i++) {
m = vals[i];
count = 0;

// Count how many times each value occurs.
for(int j=i+1; j < vals.length; j++)
if(m == vals[j]) count++;

/* If this value occurs more frequently than
the previous candidate, save it. */
if(count > oldcount) {
modeVal = m;
oldcount = count;
}
}

if(oldcount == 0)
throw new NoModeException();
else
return modeVal;
}

// Return the standard deviation of a set of values.
public static double stdDev(double[] vals) {
double std = 0.0;
double avg = mean(vals);

for(int i=0; i < vals.length; i++)
std += (vals[i]-avg) * (vals[i]-avg);

std /= vals.length;
std = Math.sqrt(std);

return std;
}

/* Compute the regression equaltion and coefficient
of correlation for a set of values. The
values represent the Y coordinate. The X
cooridinate is time (i.e., ascending increments
of 1). */
public static RegData regress(double[] vals) {
double a, b, yAvg, xAvg, temp, temp2, cor;
double vals2[] = new double[vals.length];

// Create number format with 2 decimal digits.
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);

// Find mean of Y values.
yAvg = mean(vals);

// Find mean of X component.
xAvg = 0.0;
for(int i=0; i < vals.length; i++) xAvg += i;
xAvg /= vals.length;

// Find b.
temp = temp2 = 0.0;
for(int i=0; i < vals.length; i++) {
temp += (vals[i]-yAvg) * (i-xAvg);
temp2 += (i-xAvg) * (i-xAvg);
}

b = temp/temp2;

// Find a.
a = yAvg - (b*xAvg);

// Compute the coefficient of correlation.
for(int i=0; i < vals.length; i++) vals2[i] = i+1;
cor = temp/vals.length;
cor /= stdDev(vals) * stdDev(vals2);

return new RegData(a, b, cor, "Y = " +
nf.format(a) + " + " +
nf.format(b) + " * X");
}
}


-------------------------------------------------
StatsWin
-------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;

// Process and display statistical data.
public class StatsWin extends Frame
implements ItemListener, ActionListener {

NumberFormat nf = NumberFormat.getInstance();

TextArea statsTA;
Checkbox bar = new Checkbox("Bar Graph");
Checkbox scatter = new Checkbox("Scatter Graph");
Checkbox regplot = new Checkbox("Regression Line Plot");
Checkbox datawin = new Checkbox("Show Data");

double[] data;

Graphs bg;
Graphs sg;
Graphs rp;
DataWin da;

RegData rd;

public StatsWin(double vals[]) {
data = vals; // save reference to data

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
shutdown();
}
});

// Create the File menu.
createMenu();

// Change to flow layout, centering components.
setLayout(new FlowLayout(FlowLayout.CENTER));

setSize(new Dimension(300, 240));
setTitle("Statistical Data");

rd = Stats.regress(data);

// Set the number format to 2 decimal digits.
nf.setMaximumFractionDigits(2);


// Construct output.
String mstr;
try {
// Obtain mode, if there is one.
mstr = nf.format(Stats.mode(data));
} catch(NoModeException exc) {
mstr = exc.toString();
}

String str = "Mean: " +
nf.format(Stats.mean(data)) + "\n" +
"Median: " +
nf.format(Stats.median(data)) + "\n" +
"Mode: " + mstr + "\n" +
"Standard Deviation: " +
nf.format(Stats.stdDev(data)) + "\n\n" +
"Regression equation: " + rd.equation +
"\nCorrelation coefficient: " +
nf.format(rd.cor);

// Put output in text area.
statsTA = new TextArea(str, 6, 38, TextArea.SCROLLBARS_NONE);
statsTA.setEditable(false);

// Add components to window.
add(statsTA);
add(bar);
add(scatter);
add(regplot);
add(datawin);

// Add component listeners.
bar.addItemListener(this);
scatter.addItemListener(this);
regplot.addItemListener(this);
datawin.addItemListener(this);

setVisible(true);
}

// Handle the Close menu option.
public void actionPerformed(ActionEvent ae) {
String arg = (String)ae.getActionCommand();

if(arg == "Close") {
shutdown();
}
}

// User changed a checkbox.
public void itemStateChanged(ItemEvent ie) {
if(bar.getState()) {
if(bg == null) {
bg = new Graphs(data, Graphs.BAR);
bg.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
bar.setState(false);
bg = null;
}
});
}
}
else {
if(bg != null) {
bg.dispose();
bg = null;
}
}

if(scatter.getState()) {
if(sg == null) {
sg = new Graphs(data, Graphs.SCATTER);
sg.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
scatter.setState(false);
sg = null;
}
});
}
}
else {
if(sg != null) {
sg.dispose();
sg = null;
}
}

if(regplot.getState()) {
if(rp == null) {
rp = new Graphs(data, Graphs.REGPLOT);
rp.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
regplot.setState(false);
rp = null;
}
});
}
}
else {
if(rp != null) {
rp.dispose();
rp = null;
}
}

if(datawin.getState()) {
if(da == null) {
da = new DataWin(data);
da.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
datawin.setState(false);
da = null;
}
});
}
}
else {
if(da != null) {
da.dispose();
da = null;
}
}
}

// Create the File menu.
private void createMenu()
{
MenuBar mbar = new MenuBar();
setMenuBar(mbar);

Menu file = new Menu("File");
MenuItem close = new MenuItem("Close");
file.add(close);
mbar.add(file);
close.addActionListener(this);
arrow
arrow
    全站熱搜

    Neo Chao 發表在 痞客邦 留言(0) 人氣()