我有一个工作班HoltWinters,这是我的包中的主要内容。它是一个控制台应用程序。我搜索计算机上的一个文件夹,读取该文件夹中所有文件的名称。然后我要求用户打印他想要在程序中使用的文件的名称。之后,我将此名称保存为字符串,并使用此文件进行预测。
但我需要通过Windows应用程序来完成。据我所知,我需要创建新的Java JFrame(我使用NetBeans,所以我已经使用了他们的构造函数)。我把1个JText字段和1个JButton放在那里。我想按下按钮时会发生下一件事:
但是我根本不明白怎么做:(我想,也许我的逻辑中有一些错误,或者它应该以不同的方式完成,但它是我的第一个不是控制台应用程序,我不知道该怎么做做: - (
这是我的HoltWinters课程:
package holtwinters;
import java.io.*;
import java.util.*;
import java.lang.*;
/**
St[i] = alpha * y[i] / It[i - period] + (1.0 - alpha) * (St[i - 1] + Bt[i - 1]) - overall
Bt[i] = gamma * (St[i] - St[i - 1]) + (1 - gamma) * Bt[i - 1] - trend
It[i] = beta * y[i] / St[i] + (1.0 - beta) * It[i - period] - season
Ft[i + m] = (St[i] + (m * Bt[i])) * It[i - period + m] - predictions
*/
/**
*
* @author Jane
*/
public class HoltWinters {
/**
* @param args the command line arguments
*/
/*
y - Time series data.
alpha - coeff
beta - coeff
gamma - coeff
period - 24 hours
m - future data
debug - debug values for testing
*/
public static void main( String[] args )
throws FileNotFoundException, IOException {
String path = "C:\\Users\\Jane\\Desktop";
File f = new File (path);
String[] list=f.list();
for (String str : list){
System.out.println(str);
}
BufferedReader in=new BufferedReader (new InputStreamReader(System.in));
System.out.print("Input n: ");
String sn=in.readLine();
String[] ary = sn.split(" ");
String name = null;
for(String file1: list) {
for (String ary1: ary) {
if (ary1.equals(file1)) {
System.out.println("found!");
name = sn;
}
}
}
File file = new File( path+"\\"+name );
BufferedReader br = new BufferedReader (
new InputStreamReader(
new FileInputStream( file ), "UTF-8"
)
);
String line = null;
while ((line = br.readLine()) != null) {
try {
Long y = Long.valueOf(line);
// System.out.println(y);
} catch (NumberFormatException e) {
System.err.println("Неверный формат строки!");
}
}
// long data = Long.valueOf(line);
// int change = (int) data;
// long [] y = new long [change];
int period = 24;
int m = 5;
long[] y = new long[144];
try {
Scanner scanner = new Scanner(new File(path+"\\"+name));
int i = 0;
while (scanner.hasNextLong()) {
y[i] = scanner.nextLong();
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
double sum_origin = 0;
int k=0;
do {
sum_origin = sum_origin + y[k];
k++;
} while (k<24);
//searching for alpha
double alpha = 0.01;
double a = 0.01;
double x=sum_origin;
double q;
do {
double beta = 0.3;
double gamma = 0.3;
double[] prediction = HoltWinters.forecast(y, a, beta, gamma,
period, m);
double sum_pre = sum(prediction);
q = sum_origin - sum_pre;
if (q<=x) {
x=q;
alpha = a;
}
a = a +0.01;
} while (a<0.99);
//searching for beta
double beta = 0.01;
double b = 0.01;
double x1=1000000;
double q1;
do {
double gamma = 0.3;
double[] prediction = HoltWinters.forecast(y, alpha, b, gamma,
period, m);
double sum_pre = sum(prediction);
q1 = sum_origin - sum_pre;
if (q1<=x1) {
x1=q1;
beta = b;
}
b = b +0.01;
} while (b<0.99);
//searching for gamma
double gamma = 0.01;
double g = 0.01;
double x2=1000000;
double q2;
do {
double[] prediction = HoltWinters.forecast(y, alpha, beta, g,
period, m);
double sum_pre = sum(prediction);
q2 = sum_origin - sum_pre;
if (q2<=x2) {
x2=q2;
gamma = g;
}
g = g +0.01;
} while (g<0.99);
System.out.println(alpha);
System.out.println(beta);
System.out.println(gamma);
double[] prediction = HoltWinters.forecast(y, alpha, beta, gamma,
period, m);
for(int i = period; i <= prediction.length - 1; i++) {
System.out.println(prediction[i] + " ");
}
br.close();
File flt = new File("C:\\Users\\Jane\\Desktop\\003003_prediction.txt");
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(flt)));
for(int i = period; i <= prediction.length - 1; i++) {
out.println(prediction[i] + " ");
}
out.flush();
}
public static double sum(double...values) {
double result = 0;
for (double value:values)
result += value;
return result;
}
public static double[] forecast(long[] y, double alpha, double beta,
double gamma, int period, int m, boolean debug) {
validateArguments(y, alpha, beta, gamma, period, m);
int seasons = y.length / period;
double a0 = calculateInitialLevel(y, period);
double b0 = calculateInitialTrend(y, period);
double[] initialSeasonalIndices = calculateSeasonalIndices(y, period,
seasons);
if (debug) {
System.out.println(String.format(
"Total observations: %d, Seasons %d, Periods %d", y.length,
seasons, period));
System.out.println("Initial level value a0: " + a0);
System.out.println("Initial trend value b0: " + b0);
printArray("Seasonal Indices: ", initialSeasonalIndices);
}
double[] forecast = calculateHoltWinters(y, a0, b0, alpha, beta, gamma,
initialSeasonalIndices, period, m, debug);
if (debug) {
printArray("Forecast", forecast);
}
return forecast;
}
public static double[] forecast(long[] y, double alpha, double beta,
double gamma, int period, int m) {
return forecast(y, alpha, beta, gamma, period, m, false);
}
/**
validate input
*/
private static void validateArguments(long[] y, double alpha, double beta,
double gamma, int period, int m) {
if (y == null) {
throw new IllegalArgumentException("Value of y should be not null");
}
if(m <= 0){
throw new IllegalArgumentException("Value of m must be greater than 0.");
}
if(m > period){
throw new IllegalArgumentException("Value of m must be <= period.");
}
if((alpha < 0.0) || (alpha > 1.0)){
throw new IllegalArgumentException("Value of Alpha should satisfy 0.0 <= alpha <= 1.0");
}
if((beta < 0.0) || (beta > 1.0)){
throw new IllegalArgumentException("Value of Beta should satisfy 0.0 <= beta <= 1.0");
}
if((gamma < 0.0) || (gamma > 1.0)){
throw new IllegalArgumentException("Value of Gamma should satisfy 0.0 <= gamma <= 1.0");
}
}
/**
the Holt-Winters equations
*/
private static double[] calculateHoltWinters(long[] y, double a0, double b0,
double alpha, double beta, double gamma,
double[] initialSeasonalIndices, int period, int m, boolean debug) {
double[] St = new double[y.length];
double[] Bt = new double[y.length];
double[] It = new double[y.length];
double[] Ft = new double[y.length + m];
// Initialize base values
St[1] = a0;
Bt[1] = b0;
for (int i = 0; i < period; i++) {
It[i] = initialSeasonalIndices[i];
}
// Start calculations
for (int i = 2; i < y.length; i++) {
// Calculate overall smoothing
if ((((i - period) >= 0) & (It[i]!=0))) {
St[i] = alpha * y[i] / It[i - period] + (1.0 - alpha)
* (St[i - 1] + Bt[i - 1]);
}
else {
St[i] = alpha * y[i] + (1.0 - alpha) * (St[i - 1] + Bt[i - 1]);
}
// Calculate trend smoothing
Bt[i] = gamma * (St[i] - St[i - 1]) + (1 - gamma) * Bt[i - 1];
// Calculate seasonal smoothing
if ((i - period) >= 0) {
It[i] = beta * y[i] / St[i] + (1.0 - beta) * It[i - period];
}
// Calculate forecast
if (((i + m) >= period)) {
Ft[i + m] = Math.abs(((St[i] + (m * Bt[i])) * It[i - period + m])*(-1));
}
if (debug) {
System.out.println(String.format(
"i = %d, y = %d, S = %f, Bt = %f, It = %f, F = %f", i,
y[i], St[i], Bt[i], It[i], Ft[i]));
}
}
return Ft;
}
/**
Initial Level value - St[1]
*/
public static double calculateInitialLevel(long[] y, int period) {
double sum = 0;
for (int i = 0; i < 24; i++) {
sum += (y[i]);
}
return sum / (period*period);
}
/**
Initial trend - Bt[1]
*/
public static double calculateInitialTrend(long[] y, int period) {
double sum = 0;
for (int i = 0; i < period; i++) {
sum += Math.abs((y[period + i] - y[i]));
}
return sum / (period * period);
}
/**
Seasonal Indices.
*/
public static double[] calculateSeasonalIndices(long[] y, int period,
int seasons) {
double[] seasonalAverage = new double[seasons];
double[] seasonalIndices = new double[period];
double[] averagedObservations = new double[y.length];
for (int i = 0; i < seasons; i++) {
for (int j = 0; j < period; j++) {
seasonalAverage[i] += y[(i * period) + j];
}
seasonalAverage[i] /= period;
}
for (int i = 0; i < seasons; i++) {
for (int j = 0; j < period; j++) {
averagedObservations[(i * period) + j] = y[(i * period) + j]
/ seasonalAverage[i];
}
}
for (int i = 0; i < period; i++) {
for (int j = 0; j < seasons; j++) {
seasonalIndices[i] += averagedObservations[(j * period) + i];
}
seasonalIndices[i] /= seasons;
}
return seasonalIndices;
}
/**
method to print array values
*/
private static void printArray(String description, double[] data) {
System.out.println(description);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
}
这是JFrame
package holtwinters;
/**
*
* @author Jane
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("Введите номер банкомата");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setText("Ввести");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(136, 136, 136)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(141, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("Button pressed") ;
HoltWinters other = new HoltWinters();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
答案 0 :(得分:0)
yourButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
yourButtonActionPerformed(evt);
}
});
public void yourButtonActionPerformed(java.awt.event.ActionEvent evt) {
String yourText = jTextField1.getText();
HoltWinters tempHolt = new HoltWinters();
tempHolt.methodToRun(yourText);
}
你需要经常更改代码,从dao,model和gui图层(包)开始。