有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java静态for循环?在之前执行计算

我不知道该怎么做。我正在尝试使用需要是全局变量的值执行计算。但要做到全球化,它必须是静态的。我需要for循环也是静态的,这样它就可以在数组中执行计算,但我不记得怎么做了。 最后一行代码是我目前由于“找不到符号”错误而被卡住的地方。我正试图找到一种方法,将yVal0引入该方法,以便执行计算

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RegressionGUI  extends JFrame
    implements ActionListener {
private JLabel VariableLabel = new JLabel("Select one independent Variable");

共 (3) 个答案

  1. # 1 楼答案

    由于它的格式非常糟糕,您的代码很难理解(因此我没有读过),但如果您希望在运行时计算静态变量,最好的选择是这样的:

    public static final int MY_VAR = computeValue();
    
    private static int computeValue() {
        //for loop here
    }
    
  2. # 2 楼答案

    你在找static initialization block。这是在第一次初始化类的对象之前,或者在第一次执行类的静态成员之前执行的代码块

  3. # 3 楼答案

    再一次,我怀疑您是否需要使用任何静态代码,快速查看一下您的(格式不好的)代码就可以看出,这仍然是一种需要。为什么不改为使一些数值变量类字段而不是方法局部或构造函数局部,这样就可以在类的任何非静态方法中使用它们呢

    例如

    public class RegressionGUI extends JFrame implements ActionListener {
       private JLabel VariableLabel = new JLabel("Select one independent Variable");
       private JButton X1btn = new JButton("Number of Bathrooms (X1)");
       private JButton X2btn = new JButton("Area of the site (X2)");
       private JButton X3btn = new JButton("Size of living space (X3)");
       private JButton X4btn = new JButton("Number of Garages (X4)");
       private JButton X5btn = new JButton("Number of Rooms (X5)");
       private JButton X6btn = new JButton("Number of bedrooms (X6)");
       private JButton X7btn = new JButton("Age (X7)");
       private JTextArea textArea = new JTextArea();
       private JScrollPane scrollPane = new JScrollPane(textArea);
    
       // **** added these guys
       private double[] xValues = new double[4];
       private double[] yValues = new double[4];