Public static vs private

Hi
I have 3 classes, A, B & C.
I have one variable, var, that can be used in class B and C; I have declared it in class B, and passed when I create an istance of C in B.
Then I need also to read its value in class A.
Now the ways are two (I think ...):
1. declare it as public static in class A and then use A.var in class B and C;
2. declare it as private in A and then passed to B when I create in A an istance of B and to C then I create in B an istance to C.
Considerations:
a. I don't like to declare public variables, I think is a bad way to program,
isn'it?
b. the second way is a problem when I have 10 variables (the constructors have too many parameters), right?
Could anyone help?

The problem is I tryied to find these answer in
Intenrnet, but I don't find anything.That's fine. That's why most of us are here.
My application works as this:
I have a main class (A) that have a main menu in
console style; from this class I create a new client
class (B) that receive commands from a server; if a
command is valid, B create an istance of C that
rappresents a trainer machine. In C I have all
workout variables (time, incline, speed ...).
By menu (in class A) i could pause the trainer and by
A and/or remote server I could ask the state of the
machine (C).
In your explanation above, I draw your attention to "instance". You are making instances of your classes. That being the case, your variables should probably be instance variables
NOT
public static int firstVariable = 0;BUT
protected int firstVariable = 0;You would then provide get and set methods to access the protected variable.
If you find yourself writing B b = new B() then you know you are dealing with an instance and you should avoid all static variables unless you really do mean "this value is the same across all Bs".
I have 8 state variables I could manage in that way.
The only way I have for now found is definite a
public static long vars in C (and use them in A e B
as C.state, C.time, ...) to avoid to pass 8
parameters when I create the istances from A to C.Assuming that C has eight variables and your design isn't done yet you can still pass an instance of C to the other objects. They don't need to have their method/constructor signatures changed when you add a new variable as your C object encapsulates it already.
>
Is right? Any other suggestion?Yes. Don't stick to "C.time" because that's what you've got so far. Instead, you should be using
C c = new C();
c.getTime();That way, the time variable is unique to the instance.

Similar Messages

  • Private construtor, public static method

    Hi,
    I'm having a problem trying to use a class' method. The class' constructor is private, and the methods are public static....
    I created an object that belongs to the class, but then when I try to apply the methods to the object, the do not appear (qhen I write the period). Does anybody know why this happens...
    Thanks and regards

    Ok,
    I'll show you the code I'm trying to use. In case you want to see more from it, I downloaded it from http://info.synapse.ru/software/jpitsa/
    Just to give you a more clear idea, I unzipped the jar file which contained the code, and I got two classes with the same name on the same folder (one is a read-only file). The class I'm trying to use is called "Methods". The particular method I'm trying to use from that class is the one called hilbert, which does the Hilbert Transform (which is a Mathematical transformartion for signal processing).
    Thanks for your help. Here comes my code:
    * Spectral Analysis Module
    * @author Denis Mishin ([email protected])
    package jpitsa.core;
    import java.util.LinkedList;
    public final class Methods implements Params {
        private Methods() { }
         * Discrete Fourier Transform. <BR>
         * This method can be applied to data with any data points, not only a power of 2,
         * but works significantly slower then DFFT algorithm
         * @param source the data to transform
         * @param direct true if transform is direct, false for inverse
         * @param fullSpectrum  as fourier transform is symmetrical, it is possible to use only one part of it.\
         *      then the spectrum is created for 1/2 N points. reverse transform will work pretty well.
         * @see jpitsa.core.ComplexVector
        public static ComplexVector DFT (ComplexVector source, boolean direct) {
            ComplexVector result;
            float[] resIm, resRe;
            float[] srcIm, srcRe;
            float isign = (direct == true) ? 1f : -1f;
            srcIm = source.getDataImaginaryPart();
            srcRe = source.getDataRealPart();
            int N = srcIm.length;
            float mf = (direct == true) ? 1f : 1f/(float)N;
            resIm = new float[N];
            resRe = new float[N];
            double fac;
            double f1, fCos, fSin;
            f1 = isign*2*Math.PI/(float)N;
            for (int n=0; n < N/2; n++) {
                for (int k=0; k < (N-1); k++) {
                    fac = (float)(f1*(double)(k*n));
                    fCos = Math.cos(fac);
                    fSin = Math.sin(fac);
                    resRe[n] += srcRe[k]*fCos - srcIm[k]*fSin;
                    resIm[n] += srcRe[k]*fSin + srcIm[k]*fCos;
                resRe[n] *= mf;
                resIm[n] *= mf;
                resRe[N-1-n] = resRe[n];
                resIm[N-1-n] = resIm[n];
            return new ComplexVector(resRe, resIm);
         * This method computes Discrete Fast Fourier Transform from a given
         * complex array. Return type is also a complex array.
         * Objectives: only data of 2^n points can be processed. Thus providing number of aliasing effects.
         * @see jpitsa.core.ComplexVector
        public static ComplexVector DFFT (ComplexVector source, boolean direct) {
            ComplexVector   result;
            float[] data;
            int isign, ndat;
            isign = (direct == true) ? 1 : -1;
            data = source.getPackedData();
            ndat = (data.length-1)/2;
            four1 (data, ndat, isign);
            //System.out.println("ndat="+ndat);
            // too big values .... [mar-99]
            if(!direct) {
                for(int i=0; i < ndat*2-1; i++)
                    data[i] /= ndat;
            result = new ComplexVector();
            result.setPackedData(data);
            return result;
         * Computes a spectrum of TimeSeries
         * @return spectrum truncated to Nyquist frequency
        public static ComplexVector spectrum(TimeSeries source) {
          float sampfreq = source.getSamplingFrequency();
          ComplexVector spec = DFFT(new ComplexVector(source.getData(),null), true);
          float[] srcReal, srcImag, tgtReal, tgtImag;
          srcReal = spec.getDataRealPart();
          srcImag = spec.getDataImaginaryPart();
          tgtReal = new float[srcReal.length/2];
          tgtImag = new float[srcImag.length/2];
          System.arraycopy(srcReal, 0, tgtReal, 0, tgtReal.length);
          System.arraycopy(srcImag, 0, tgtImag, 0, tgtImag.length);
          return new ComplexVector(tgtReal, tgtImag);
         * Return given spectrum part of time series object
         * @param source source data
         * @param part defines which part of transform to extract (AMPLITUDE, PHASE, REAL, IMAGINARY)
         * @return spectrum (FrequencySeries) object
        public static FrequencySeries spectrum(TimeSeries source, int part) {
            ComplexVector spec = spectrum(source);
            float sPart[] = extractPart(spec, part);
            sPart[0] = sPart[1];
            return new FrequencySeries(sPart,source.getSamplingFrequency()/((float)(2*sPart.length)));
        public static FrequencySeries spectrum(TimeSeries source, int part, int smooth_win) {
            ComplexVector spec = spectrum(source);
            float sPart[] = extractPart(spec, part);
            sPart[0] = sPart[1];
            sPart = smooth(sPart, smooth_win);
            return new FrequencySeries(sPart, source.getSamplingFrequency()/((float)(2*sPart.length)));
    public static FrequencySeries power_spectrum(TimeSeries src)
        float tr_wrk[];              /* pntr to work trace                   */
        float tr_tap[];              /* pntr to taper                        */
        float tr_ans[];              /* pntr to answer                       */
    //    float *tr_src[];                /* pntr to source trace               */
        float t_samp;               /* sampling rate of trace               */
        float delta_f;          /* delta f of resulting power spec     */
        float wss;               /* window squared and summed          */
        float sumsq;          /* sum of the input trace squared     */
        float avesq;          /* ave of the input trace squared     */
        float pow_sum;          /* PSD Sum                    */
        int i1, i2;                 /* index of the zoom in spr_zoom        */
        int n1, n2, n3, n4;         /* taper window size                    */
        int i,j;                    /* loop vars                            */
        int index;                  /* index into data from cha_list        */
        int n_dat;                  /* size of trace                        */
        int done;                   /* tells us if we are done with io      */
        int io_res;                 /* result of an io operation            */
        int n_fft;                  /* number of points in fft window       */      
        int n_chk;                  /* temp to check that n_fft is pwr of 2 */
        int i_st;               /* start of window for fft          */
        int ask_each;               /* see if we ask for input each loop    */
        int io_taper;               /* taper method we are going to use     */
        boolean zero_pad;               /* true when we have to zero pad window */
        int sc_type;          /* type of scale ie lin-lin          */
        int selection_method;     /* selection used for zoom          */
        int status;               /* status of zoom               */
        int n;               /* number of fft's used for answer     */
          get the size of the trace
         float[] tr_src = src.getData();
         n_dat = tr_src.length;
         i1 = 0; i2 = tr_src.length-1;
         n_fft = next2power(n_dat); // check!!!!
         dt_copy_header(buffer[0],data[index]);
         dt_copy_header(buffer[1],data[index]);
         dt_copy_header(buffer[2],data[index]);
         dt_head_access(buffer[0],RCD_NDAT,(void *)&n_fft);
         dt_head_access(buffer[1],RCD_NDAT,(void *)&n_fft);
         n = n_fft/2 + 1;
    //     dt_head_access(buffer[2],RCD_NDAT,(void *)&n);
         tr_wrk = new float[n_fft+1];
         System.arraycopy(tr_src, 0, tr_wrk, 0, tr_src.length);
         tr_tap = new float[tr_wrk.length];
         System.arraycopy(tr_wrk, 0, tr_tap, 0, tr_wrk.length);
         //tr_wrk = dt_trace_access(buffer,0,    0);
         //tr_tap = dt_trace_access(buffer,1    ,0);
         //tr_tap = // taper_it
         tr_ans = new float[n];
         //tr_ans = dt_trace_access(buffer,2    ,0);
         //tr_src = dt_trace_access(data  ,index,0);
          calculate the mean squared amplitude
         sumsq = 0f;
         for (j=i1; j<i2; j++) {
             sumsq += tr_src[j] * tr_src[j];
         avesq = sumsq / (float)(n_dat);
          get the taper values.  Buffer 0 gets tapered even thought there is nothing there
         n1 = 0;
         n2 = n3 = n_fft/2 - 1;
         n4 = n_fft - 1;
         Taper.doTapering(tr_tap, n1, n2, n3, n4, n_fft, WELCH_WINDOW);
          init the result
         for (j=0; j<n_fft/2; j++) {
             tr_ans[j] = 0;
          calculate wss (window squared and summed)
         wss = 0f;
         for (j=0; j<n_fft; j++) {
             wss += tr_tap[j] * tr_tap[j];
         wss *= (float)n_fft;
          calculate fft's until we need to pad with zeros
         t_samp = src.getSamplingInterval();
         zero_pad = false;
         i_st = i1;
         n = 0;
         while (!zero_pad) {
              load work array and taper
             for (j=0; j<n_fft; j++) {
              if ((i_st + j) > i2) {
                  tr_wrk[j] = 0f;
                  zero_pad = true;
              } else {
                  tr_wrk[j] = tr_src[i_st+j] * tr_tap[j];
              calculate fft
             n++;
             realft(tr_wrk,n_fft/2,1);
              accum results
             tr_ans[0] += tr_wrk[0]*tr_wrk[0];
             for (j=2; j<n_fft; j+=2) {
              tr_ans[j/2] += 2.0 * (tr_wrk[j]*tr_wrk[j] + tr_wrk[j+1]*tr_wrk[j+1]);
             tr_ans[n_fft/2] += tr_wrk[1]*tr_wrk[1];
             i_st += n_fft/2;
          normalize
         for (j=0; j<=n_fft/2; j++) {
             tr_ans[j] /= ((float)n*wss);
          integrate result
         delta_f = t_samp*n_fft;
         pow_sum = tr_ans[0];
         for (j=1; j<n_fft/2; j++) {
             pow_sum += tr_ans[j];
         pow_sum += tr_ans[n_fft/2];
          convert to units^2/Hz
         for (j=0; j<n_fft/2; j++) {
             tr_ans[j] = tr_ans[j]/delta_f;
         //delta_f = (t_samp*n_fft);
        return new FrequencySeries(tr_ans, src.getSamplingFrequency()/ (float) tr_ans.length);
        //source.getSamplingFrequency()/((float)(2*sPart.length))
        public static FrequencySeries powspec1(TimeSeries src, int m) {
            float[] rawdata = src.getData();
            float[] res = PowSpec.spctrm(rawdata, m, rawdata.length/2, true);
            return new FrequencySeries(res, src.getSamplingFrequency()/2f);
         * returns coherence spectrum of two traces
         * result is a complex vector truncated to Nyquist frequency
        public static ComplexVector coherenceSpectrum (TimeSeries trace1, TimeSeries trace2) {
          if (trace1.getSamplingFrequency() != trace2.getSamplingFrequency())
            throw new IllegalArgumentException("Sampling freqs do not match");
          if (trace1.getDataLength() != trace2.getDataLength())
            throw new IllegalArgumentException("vectors length do not match");
          ComplexVector spec1, spec2, cohSpec;
          spec1 = spectrum(trace1);
          spec2 = spectrum(trace2);
          return (ComplexVector)spec1.mul(spec2.conjugate());
         * returns a given part of coherence spectrum of two traces
        public static FrequencySeries coherenceSpectrum (TimeSeries trace1, TimeSeries trace2, int part) {
          float[] res = extractPart(coherenceSpectrum(trace1,trace2), part);
          return new FrequencySeries(res, trace1.getSamplingFrequency()/(float)(2*res.length));
         * XCorellation of two vectors
         * @param v1 first vector
         * @param v2 second vector
        public static Vector1D corellation(Vector1D v1, Vector1D v2) {
          if (v1.getDataLength() != v2.getDataLength())
            throw new IllegalArgumentException("vectors length do not match");
          ComplexVector sp1, sp2, res;
          sp1 = DFFT(new ComplexVector(v1.getData(),null), true);
          sp2 = DFFT(new ComplexVector(v2.getData(),null), true);
          res = DFFT((ComplexVector)sp1.mul(sp2.conjugate()), false);
          float[] data = res.getDataAmplitudePart();
          float[] data2 = new float[data.length/2];
          System.arraycopy(data,0, data2, 0, data2.length); data2[0] = data2[1];     
          return new Vector1D(data2);
         * Computes a sonogram for a trace
         * This is an optimized algorithm,
        public static Matrix sonogram(TimeSeries data, float stepSec, float window, int taperType, float taperFraction) {
          LinkedList frq = new LinkedList();
          float sampling = data.getSamplingFrequency();
          int step = Math.round(sampling*stepSec);
          DataWindow currentWindow = data.getWindow();
          data.setMessagesAllowed(false);
          DataWindow win = new DataWindow();
          win.startOffset = currentWindow.startOffset;
          win.length      = Math.round(window*sampling);
          boolean computing = true;
          float[] tgt = null;
          int leng = 0;
          if (step < 1)
            step = 1;
          System.err.println("COMPUTING SONOGRAM: step="+stepSec+" ("+step+") length="+window+" ("+win.length+")");
          while (computing) {
            data.setWindow(win);
            ComplexVector spec;
            float[] src = taper(data, taperFraction, taperType).getTotalData();
            spec = DFFT(new ComplexVector(src,null), DIRECT);
            leng = spec.getDataPointsNumber() / 2;
            tgt = new float[leng];
            spec.getDataAmplitudePart(tgt);
            src = extractPart(spec, AMPLITUDE, tgt);
            tgt = new float[ftlen];
            System.arraycopy(src,0,tgt,0,tgt.length);
            tgt = src;
            // --- THIS CODE SHOULD BE REMOVED
            for (int i=0; i < tgt.length; i++)
                tgt[i] = (tgt[i] > 0) ? (float)Math.log(tgt) : tgt[i];
    //tgt = smooth(tgt, Math.round(.05f*tgt.length));
    // --- THIS CODE SHOULD BE REMOVED
    //System.err.println("Step: "+win.startOffset+":"+win.length);
    frq.add(tgt);
    win.startOffset += step;
    if (win.getEnd() > currentWindow.getEnd())
    computing = false;
    data.setWindow(currentWindow);
    data.setMessagesAllowed(true);
    Matrix m;
    m = new Matrix(frq.size(), leng);
    for (int i=0; i < frq.size(); i++)
    m.setColumn(i,(float[])frq.get(i));
    m.setBounds(data.getActiveRegionOffsetSeconds(), data.getActiveRegionOffsetSeconds()+data.getDuration(),
    0f, data.getSamplingFrequency()/2f);
    return m;
    public static double[] toDouble(float[] data) {
    double[] ret = new double[data.length];
    for (int i=0; i < data.length; i++)
    ret[i] = data[i];
    return ret;
    * Differentiate a trace
    public static TimeSeries differentiate (TimeSeries src) {
    int ndat;
    float t_samp;
    int i;
    float[] tr;
    float buff;
    float buff0;
    ndat = src.getDataLength();
    t_samp = 1f/src.getSamplingFrequency();
    tr = src.getData();
    buff0 = tr[0];
    tr[0] *= 2f/t_samp;
    for(i=1;i<ndat;i++)
    buff = tr[i];
    tr[i] = (tr[i] - buff0)/t_samp;
    buff0 = buff;
    return (TimeSeries)src.newInstance(tr);
    * Integrate a trace
    * @param source source trace
    * @param method method to use: Trapezoid or Tick rule
    * @return integrated trace
    public static TimeSeries integrate(TimeSeries source, int method) {
    if (method == Params.TRAPEZOID)
    return Integrate.trapRule(source);
    else if (method == Params.TICK)
    return Integrate.tickRule(source);
    else
    throw new IllegalArgumentException("Invalid method "+method);
    * Integrates a trace using Tick's rule
    * @param source source trace
    * @return integrated trace
    public static TimeSeries integrate(TimeSeries source) {
    return integrate(source, Params.TICK);
    * Trace resampling
    * @param data source trace
    * @param newSampFreq new sampling frequency
    * @return new resampled trace
    public static TimeSeries resample(TimeSeries data, float newSampFreq) {
    float sampFreq = data.getSamplingFrequency();
    float[] newdata = interpolate(data.getData(), sampFreq, newSampFreq);
    TimeSeries res = (TimeSeries)data.newInstance(newdata);
    res.samplingFrequency = newSampFreq;
    return res;
    * Generic moving average window smoothing. <BR>
    * @param src source array
    * @param nx2 half window length
    public static Vector1D smooth(Vector1D src, int nx2) {
    return src.newInstance( smooth(src.getData(), nx2) );
    * Generic moving average window smoothing
    * @param src source array
    * @param nx2 half window length
    public static float[] smooth(float[] src, int nx2) {
    int ndat = src.length;
    float[] res = new float[ndat];
    //System.arraycopy(src, 0, res, 0, ndat);
    float sum1, sum2;
    int i, j, k;
    //System.err.println("NX2 = "+nx2);
    jpitsa.Out.cerr.println("data = "+src.length+"NX2 = "+nx2);
    for(i=nx2;i<=ndat-(nx2+1);i++) {
    sum1=0f; sum2=0f;
    for(j=1;j<=nx2;j++) {
    sum1 = sum1 + src[i-j];
    sum2 = sum2 + src[i+j];
    res[i] = (sum1+sum2+src[i])/(float)(2*nx2+1);
    for(i=1;i<=nx2-1;i++) {
    sum1=0f;
    sum2=0f;
    k = 0;
    for(j=1;j<=i;j++) {
    sum1 = sum1+ src[i-j];
    sum2 = sum2+ src[i+j];
    k = j;
    res[i] = (sum1+sum2+src[i])/(float)(2*k+1);
    for(i=1;i<=nx2-1;i++) {
    sum1 = sum2 = 0f;
    k = 0;
    for(j=1;j<=i;j++) {
    sum1 = sum1+ src[ndat-1-i-j];
    sum2 = sum2+ src[ndat-1-i+j];
    k = j;
    res[ndat-1-i] = (sum1+sum2+src[ndat-1-i])/(float)(2*k+1);
    res[ndat-1] = src[ndat-1];
    res[0] = src[0];
    return res;
    * Generic 4-point spline interpolation method.
    * @param data source data
    * @param oldSampFreq source sampling frequency (1/sampling interval)
    * @param newSampFreq target sampling frequency
    public static float[] interpolate(float[] data, // source data
    float oldSampFreq, // old sampling freq. [Hz]
    float newSampFreq) // new samp. freq. [Hz]
    int n_int = 4; /* degree of polynomial for interpoltion */
    float xa[]= new float[n_int+1]; /* interpolation buffer */
    float ya[]= new float[n_int+1]; /* interpolation buffer */
    int closest_sample=-1, int_start_sample=-1;
    float delta_value = 0f; /* error estimate for interpolated value */
    // this is because PITSA and JPITSA use different schemes for sampling freq. storing
    float t_samp_old = 1f / oldSampFreq;
    float t_samp_new = 1f / newSampFreq;
    int ndat = data.length;
    float x1=t_samp_old/t_samp_new;
    x1 *= (float)ndat;
    int ndat2 = Math.round(x1+5e-1f); // Number of data in new arrary
    float[] tr1 = data;
    float[] b1 = new float[ndat2];
    float[] prom_res= new float[2]; // temp. buffer for polint() procedure
    // 4-point Spline interpolation procedure
    float new_x;
    for (int j = 0; j < ndat2;j++){
    new_x = (float)j*t_samp_new;
    /* determine index of closest sample in trace */
    closest_sample = (int)(new_x/t_samp_old);
    if ((closest_sample >= (int)((float)n_int/2.)) &&
    (closest_sample <= ndat - (int)((float)n_int/2.) - 1))
    int_start_sample = closest_sample - (int)((float)n_int/2.) - 1;
    }else if (closest_sample < (int)((float)n_int/2.)) {
    int_start_sample = -1;
    }else if (closest_sample > ndat - (int)((float)n_int/2.) - 1) {
    int_start_sample = ndat -1 - n_int;
    for (int jj = 1;jj <= n_int; jj++) {
    ya[jj] = tr1[int_start_sample + jj];
    xa[jj] = (int_start_sample + jj)*t_samp_old;
    prom_res[0] = x1; prom_res[1] = delta_value;
    polint(xa,ya,n_int,new_x, prom_res);
    b1[j] = x1 = prom_res[0]; delta_value = prom_res[1];
    return b1;
    * Generic 4-point spline interpolation method.
    * @param data source data
    * @param newLength number of points in a new array
    public static float[] interpolate(float[] data, int newLength) {
    int n_int = 4; /* degree of polynomial for interpoltion */
    float xa[]= new float[n_int+1]; /* interpolation buffer */
    float ya[]= new float[n_int+1]; /* interpolation buffer */
    int closest_sample=-1, int_start_sample=-1;
    float delta_value = 0f; /* error estimate for interpolated value */
    // this is because PITSA and JPITSA use different schemes for sampling freq. storing
    float t_samp_old = 1f / oldSampFreq;
    float t_samp_new = 1f / newSampFreq;
    int ndat = data.length;
    float x1=t_samp_old/t_samp_new;
    x1 *= (float)ndat;
    int ndat2 = Math.round(x1+5e-1f); // Number of data in new arrary
    int ndat = data.length;
    int ndat2 = newLength;
    float t_samp_old = 1f;
    float t_samp_new = ((float)ndat)/((float)ndat2);
    float x1 = (float)ndat2;
    float[] tr1 = data;
    float[] b1 = new float[ndat2];
    float[] prom_res= new float[2]; // temp. buffer for polint() procedure
    // 4-point Spline interpolation procedure
    float new_x;
    for (int j = 0; j < ndat2;j++){
    new_x = (float)j*t_samp_new;
    /* determine index of closest sample in trace */
    closest_sample = (int)(new_x/t_samp_old);
    if ((closest_sample >= (int)((float)n_int/2.)) &&
    (closest_sample <= ndat - (int)((float)n_int/2.) - 1))
    int_start_sample = closest_sample - (int)((float)n_int/2.) - 1;
    }else if (closest_sample < (int)((float)n_int/2.)) {
    int_start_sample = -1;
    }else if (closest_sample > ndat - (int)((float)n_int/2.) - 1) {
    int_start_sample = ndat -1 - n_int;
    for (int jj = 1;jj <= n_int; jj++) {
    ya[jj] = tr1[int_start_sample + jj];
    xa[jj] = (int_start_sample + jj)*t_samp_old;
    prom_res[0] = x1; prom_res[1] = delta_value;
    polint(xa,ya,n_int,new_x, prom_res);
    b1[j] = x1 = prom_res[0]; delta_value = prom_res[1];
    return b1;
    * Butterworth Band Pass Filter
    * implements Band, Low and High Pass filters
    * All three Butterworth filters are recursive time domain filters
    * using the bilinear z-transform design after Stearns (1984)
    * They are applied in section of 30 dB/decade or 12 Db/octave for
    * the slope of the transition band. They may be given zero phase
    * characteristic by filterin the reversed filtered time seris
    * again (forwards-backwards filtering)
    * Finally, the trace is reversed to its original orientation
    * based on spr_bp_bworth (spr/spr_bpbt.c)
    * @author Denis Mishin ([email protected]) - Java code
    * @author PITSA team - original C code
    * @param trace input trace
    * @param flo low cut corner frequency [Hz]
    * @param fhi high cut corner frequency [Hz]
    * @param ns number of filter passes [Hz]
    * @param is_zph TRUE -> zero phase filter
    * @return new filtered trace
    public static TimeSeries bandpassFilter(TimeSeries trace,
    float flo,
    float fhi,
    int ns,
    boolean is_zph)
    final int MAX_SEC = 10;
    int i, k; /* index */
    int n,m,mm;
    int ndat; /* number of points in trace */
    double tsa;
    double a[] = new double[MAX_SEC+1];
    double b[] = new double[MAX_SEC+1];
    double c[] = new double[MAX_SEC+1];
    double d[] = new double[MAX_SEC+1];
    double e[] = new double[MAX_SEC+1];
    double f[][] = new double[MAX_SEC+1][6];
    double temp;
    double c1,c2,c3;
    double w1,w2,wc,q,p,r,s,cs,x;
    float tr[];
    ndat = trace.getDataLength();
    tsa = 1f / trace.getSamplingFrequency();
    tr = trace.getData();
    // remove mean
    float mean = mean(tr);
    for (i=0; i < tr.length; i++)
    tr[i] -= mean;
    /* design filter weights */
    /* bandpass */
    w1 = java.lang.Math.sin(flo*java.lang.Math.PI*tsa)/java.lang.Math.cos(flo*java.lang.Math.PI*tsa);
    w2 = java.lang.Math.sin(fhi*java.lang.Math.PI*tsa)/java.lang.Math.cos(fhi*java.lang.Math.PI*tsa);
    wc=w2-w1;
    q=wc*wc +2.0*w1*w2;
    s=w1*w1*w2*w2;
    for (k=1;k<=ns;k++)
    c1 = (float)(k+ns);
    c2 = (float)(4*ns);
    c3 = (2.0*c1-1.0)*java.lang.Math.PI/c2;
    cs = java.lang.Math.cos(c3);
    p = -2.0*wc*cs;
    r = p*w1*w2;
    x = 1.0+p+q+r+s;
    a[k]= wc*wc/x;
    b[k]= (-4.0 -2.0*p+ 2.0*r+4.0*s)/x;
    c[k]= (6.0 - 2.0*q +6.0*s)/x;
    d[k]= (-4.0 +2.0*p -2.0*r +4.0*s)/x;
    e[k]= (1.0 - p q-r s)/x;
    /* set initial values to 0 */
    for(n=0;n<=MAX_SEC;n++)
    for(m=0;m<=5;m++)
    f[n][m]=0.0;
    /* filtering */
    for (m=1;m<=ndat;m++) {
    f[1][5]= tr[m-1];
    /* go thru ns filter sections */
    for(n=1;n<=ns;n++)
    temp=a[n]*(f[n][5]-2.0*f[n][3] +f[n][1]);
    temp=temp-b[n]*f[n+1][4]-c[n]*f[n+1][3];
    f[n+1][5]=temp-d[n]*f[n+1][2]-e[n]*f[n+1][1];
    /* update past values */
    for(n=1;n<=ns+1;n++)
    for(mm=1;mm<=4;mm++)
    f[n][mm]=f[n][mm+1];
    /* set present data value and continue */
    tr[m-1] = (float)f[ns+1][5];
    // System.out.println("tr ["+(m-1)+"] = "+tr[m-1]);
    if (is_zph == true) {
    /* filtering reverse signal*/
    for (m=ndat;m>=1;m--) {
    f[1][5]= (double)tr[m-1];
    /* go thru ns filter sections */
    for(n=1;n<=ns;n++)
    temp=a[n]*(f[n][5]-2.0*f[n][3] +f[n][1]);
    temp=temp-b[n]*f[n+1][4]-c[n]*f[n+1][3];
    f[n+1][5]=temp-d[n]*f[n+1][2]-e[n]*f[n+1][1];
    /* update past values */
    for(n=1;n<=ns+1;n++)
    for(mm=1;mm<=4;mm++)
    f[n][mm]=f[n][mm+1];
    /* set present data value and continue */
    tr[m-1] = (float)f[ns+1][5];
    // restore mean
    for (i=0; i < tr.length; i++)
    tr[i] += mean;
    return (TimeSeries)trace.newInstance(tr);
    * Gaussian filter. <BR>
    * Removes mean by default
    public static TimeSeries gaussianFilter(TimeSeries src, float fCent, float alpha) {
    return gaussianFilter(src, fCent, alpha, true);
    * Gaussian bandpass filter
    * @param src source trace
    * @param fCent central frequency value
    * @param alpha bandwidth
    * @param rmean remove mean first flag
    * @return new filtered vector
    public static TimeSeries gaussianFilter(TimeSeries src, float fCent, float alpha, boolean rmean) {
    float[] fc = new float[1]; fc[0] = fCent;
    float[] al = new float[1]; al[0] = alpha;
    return gaussianFilter(src, fc, al, rmean);
    * Gaussian bandpass filter
    * @param src source trace
    * @param fCent central frequency values
    * @param alpha bandwidths
    public static TimeSeries gaussianFilter(TimeSeries src, float fCent[], float alpha[], boolean rmean) {
    float[] sourceData = src.getData();
    float mean = 0f;
    int i;
    if (rmean) {
    mean = mean(sourceData);
    for (i=0; i < sourceData.length; i++)
    sourceData[i] -= mean;
    ComplexVector spec = DFFT(new ComplexVector(src.getData(),null), true);
    int npoints = spec.getDataPointsNumber();
    float nyq = src.getSamplingFrequency()/2f;
    // ---- computing the Gaussian distribution function
    float[] gaus = new float[npoints];
    float freqIncrement = (2f*nyq)/((float)npoints);
    int cp = 0; float f = 0f;
    while (f <= nyq && cp < (npoints/2) ) {
    gaus[cp] = Filter.gaussianWindow(f,fCent,alpha);
    cp++; f += freqIncrement;
    int last_index = gaus.length-1;
    for (cp=0; cp < (npoints/2); cp++)
         gaus[last_index - 1] = gaus[cp];
    float[] real = extractPart(spec,Params.REAL);
    float[] imag = extractPart(spec,Params.IMAGINARY);
    //System.out.println("Gaus: real.length="+real.length+" spec.length="+npoints+
    //     " stop at "+f+" nyq="+nyq);
    real = multiplicate(real,gaus);
    imag = multiplicate(imag,gaus);
    //real = glue(real, invert(real));
    //imag = glue(imag, invert(imag));
    ComplexVector inv = DFFT(new ComplexVector(real,imag), Params.INVERSE);
    real = extractPart(inv, Params.REAL);
    float[] data = new float[real.length/2];
    System.arraycopy(real,0,data,0,data.length);
    TimeSeries result = new TimeSeries(data, nyq*2f);
    float[] data = sourceData;
    System.arraycopy(real,0,data,0,data.length);
    if (rmean) {
    for (i=0; i < data.length; i++)
    data[i] += mean;
    TimeSeries result = (TimeSeries)src.newInstance(data);
    return result;
    * Discretisation of source trace data
    * Discretization will treat the input trace as a pseudo-continuous trace from which

  • Proper setup for a network with Public Static IPs and Private IPs

    hello all-
    i am trying to setup a network with public static IP addresses and local (internal) IP addresses with 192.168.xxx.xxx format. i will try to explain as best i can how i have it set up and what my issues are.
    i have COX business services in my home and 8 static public IPs assigned to me. i have tried setting this up and everything internally (192.168.xxx.xxx) works fine and all the devices can get to the outside world fine but when i try to access ANY of the devices on the public IPs from outside the network i get absolutely nothing. the browser just times out and i cannot ping the devices even though COX can see and says the devices are bridging over. COX is unable to get a response when they ping the devices either.
    one of the devices is a Synology NAS with one Ethernet port that is using a public IP and the other using a 192.168.xxx.xxx address. when the Ethernet port is setup using a static public IP COX can see it but they get no response from a ping and when they go to the address to get the login page the browser times out. when i reconfigure the port for DHCP it grabs a public DHCP address and when COX pings that they get a response AND they are able to type the DHCP adress in their browser and get to the login page no problem. when i switch back to the static IP they can see it but again are unable to get a response from a ping and are unable to go to the login page.
    my setup is:
    COX Modem (only has 1 Ethernet port) ====>> 8 port NETGEAR Gigabit switch (all devices with Public IPs are plugged into the NETGEAR switch)
    NETGEAR switch ====>> WAN Port on Airport Extreme (latest version w/all software updates)
    LAN Port Airport Extreme ====>> CISCO 2960 48 port Gigabit Switch (all internal devices are plugged into the CISCO switch)
    like i said everything with the 192.168.xxx.xxx connects and i can connect to just fine but none of the devices with public static IPs can be pinged even though COX can see them bridging over. i have tried all new cables on the devices and that didn't work so it has to be something with my setup.
    do i need to add another router to this configuration because i have extra airport extremes lying around i can use if someone could just tell me how the setup should be. i also have a few ports open on the CISCO switch; is there a way i can use it for the 4-5 devices that have public IPs? or will that cause a problem with all the other devices plugged into it with the 192.168.xxx.xxx IP addresses?
    i'm not a networking guru (obviously) so if you are able to help me get this setup properly can you try not to use Doctoral Level syntax in your response? i would greatly appreciate it!
    i appreciate any and all help... thx in advance!

    Duplicate posts. 
    Go HERE.

  • How to call java with public static void main(String[] args) throws by jsp?

    how do i call this from jsp? <%spServicelnd temp = new spServicelnd();%> does not work because the program has a main. can i make another 2nd.java to call this spServiceInd.java then call 2nd.java by jsp? if yes, how??? The code is found below...
    import java.net.MalformedURLException;
    import java.io.IOException;
    import com.openwave.wappush.*;
    public class spServiceInd
         private final static String ppgAddress = "http://devgate2.openwave.com:9002/pap";
         private final static String[] clientAddress = {"1089478279-49372_devgate2.openwave.com/[email protected]"};
    //     private final static String[] clientAddress = {"+639209063665/[email protected]"};
         private final static String SvcIndURI = "http://devgate2.openwave.com/cgi-bin/mailbox.cgi";
         private static void printResults(PushResponse pushResponse) throws WapPushException, MalformedURLException, IOException
              System.out.println("hello cze, I'm inside printResult");
              //Read the response to find out if the Push Submission succeded.
              //1001 = "Accepted for processing"
              if (pushResponse.getResultCode() == 1001)
                   try
                        String pushID = pushResponse.getPushID();
                        SimplePush sp = new SimplePush(new java.net.URL(ppgAddress), "SampleApp", "/sampleapp");
                        StatusQueryResponse queryResponse = sp.queryStatus(pushID, null);
                        StatusQueryResult queryResult = queryResponse.getResult(0);
                        System.out.println("Message status: " + queryResult.getMessageState());
                   catch (WapPushException exception)
                        System.out.println("*** ERROR - WapPushException (" + exception.getMessage() + ")");
                   catch (MalformedURLException exception)
                        System.out.println("*** ERROR - MalformedURLException (" + exception.getMessage() + ")");
                   catch (IOException exception)
                        System.out.println("*** ERROR - IOException (" + exception.getMessage() + ")");
              else
                   System.out.println("Message failed");
                   System.out.println(pushResponse.getResultCode());
         }//printResults
         public void SubmitMsg() throws WapPushException, IOException
              System.out.println("hello cze, I'm inside SubmitMsg");          
              try
                   System.out.println("hello cze, I'm inside SubmitMsg (inside Try)");                         
                   //Instantiate a SimplePush object passing in the PPG URL,
                   //product name, and PushID suffix, which ensures that the
                   //PushID is unique.
                   SimplePush sp = new SimplePush(new java.net.URL(ppgAddress), "SampleApp", "/sampleapp");
                   //Send the Service Indication.
                   PushResponse response = sp.pushServiceIndication(clientAddress, "You have a pending Report/Request. Please logIn to IRMS", SvcIndURI, ServiceIndicationAction.signalHigh);
                   //Print the response from the PPG.
                   printResults(response);
              }//try
              catch (WapPushException exception)
                   System.out.println("*** ERROR - WapPushException (" + exception.getMessage() + ")");
              catch (IOException exception)
                   System.out.println("*** ERROR - IOException (" + exception.getMessage() + ")");
         }//SubmitMsg()
         public static void main(String[] args) throws WapPushException, IOException
              System.out.println("hello cze, I'm inside main");
              spServiceInd spsi = new spServiceInd();
              spsi.SubmitMsg();
         }//main
    }//class spServiceInd

    In general, classes with main method should be called from command prompt (that's the reason for main method). Remove the main method, put the class in a package and import the apckage in your jsp (java classes should not be in the location as jsps).
    When you import the package in jsp, then you can instantiate the class and use any of it's methods or call the statis methods directly:
    <%
    spServiceInd spsi = new spServiceInd();
    spsi.SubmitMsg();
    %>

  • Static VS Private constructor in singleton

    Dear All
    Can u tell me waht is the basic adiffernce B/w static methpd call and singleton pattern.
    Even in bothe the case we carete only one ibstance.

    For me, I like to use singleton when I need to
    perform some things inside the constructor. Butthere
    is other reason, more important: if one day youneed
    to modify to a "simple class patern", that is,
    with
    a
    simple constructor, this maintenance will be
    relativelly easy if you use singleton.And again, to me, none of this makes any sense.How
    is maintenance eased by placing code in a
    constructor? Why not in the static facade? Whynot
    in a static initializer? They are all equally'easy'
    IMO.
    suppose the following static method, that is using
    the static method of TheClass:
    public static void method() {
    TheClass.staticMethod();
    }Now you have to change, that is, the class now has to
    be a class with more than one instance, because of
    the change in the business rule of your system.
    Therefore, not only one instance anymore will be
    used. The maintenance of your system will be more
    complicated, doesn�t it? See below:
    private TheClass objClass;
    public static void method() {
    //ooops, it won�t compile
    objClass.staticMethod();
    }If you develop your system based on singleton
    pattern, you will be more prepared for this kind of
    maintenance.
    Of course, there are other solutions for this unlucky
    situation. Actually, this problem occur when you are
    developing a system, and the business rules are not
    so definitive yet, so changes in these rules are
    happening with a relative frequency. I am just saying
    a probably unlucky situation that might happen.I fail to see how you can do anything but alter the class and its dependencies if the requirements change. Is this not always the case? How does having a static method (or a Singleton) obviate the issue any more over any other type of class, or even switching between the types?
    How does making the object a Singleton 'prepare' me for change? In your mind, the dot-notation may be convenient over writing 'new', but other than that, I can't see how.
    - Saish

  • Public static BookDB instance() - java book store

    hi, can some one explain what is the use of instance function. ( the code is from sun's Duke bookstore example )
    public static BookDB instance () {
    if (onlyInstance == null)
    onlyInstance = new BookDB();
    return onlyInstance;
    thanks..

    hello,baalaji
    This is a "singleton" design pattern.
    This pattern will make sure there is no more than one instance of BookDB class in the JVM.
    I am sure that you do not display another important phrase of codes---construction method. Have a look at this method, there must be:private BookDB(){
    } This private construction method makes sure no one could new an instance of this class through a "new" keywords. The only method can new an instance is through BookDBinstance()!
    Good luck and enjoy Java!
    Wang Yu
    Developer Technical Support
    Sun Microsystems
    http://sun.com/developers/support

  • Using public static object for locking thread shared resources

    Lets Consider the example,
    I have two classes
    1.  Main_Reader -- Read from file
    public  class Main_Reader
         public static object tloc=new object();
           public void Readfile(object mydocpath1)
               lock (tloc)
                   string mydocpath = (string)mydocpath1;
                   StringBuilder sb = new StringBuilder();
                   using (StreamReader sr = new StreamReader(mydocpath))
                       String line;
                       // Read and display lines from the file until the end of 
                       // the file is reached.
                       while ((line = sr.ReadLine()) != null)
                           sb.AppendLine(line);
                   string allines = sb.ToString();
    2. MainWriter -- Write the file
    public  class MainWriter
          public void Writefile(object mydocpath1)
              lock (Main_Reader.tloc)
                  string mydocpath = (string)mydocpath1;
                  // Compose a string that consists of three lines.
                  string lines = "First line.\r\nSecond line.\r\nThird line.";
                  // Write the string to a file.
                  System.IO.StreamWriter file = new System.IO.StreamWriter(mydocpath);
                  file.WriteLine(lines);
                  file.Close();
                  Thread.Sleep(10000);
    In main have instatiated two function with two threads.
     public string mydocpath = "E:\\testlist.txt";  //Here mydocpath is shared resorces
             MainWriter mwr=new MainWriter();
             Writefile wrt=new Writefile();
               private void button1_Click(object sender, EventArgs e)
                Thread t2 = new Thread(new ParameterizedThreadStart(wrt.Writefile));
                t2.Start(mydocpath);
                Thread t1 = new Thread(new ParameterizedThreadStart(mrw.Readfile));
                t1.Start(mydocpath);
                MessageBox.Show("Read kick off----------");
    For making this shared resource thread safe, i am using  a public static field,
      public static object tloc=new object();   in class Main_Reader
    My Question is ,is it a good approach.
    Because i read in one of msdn forums, "avoid locking on a public type"
    Is any other approach for making this thread safe.

    Hi ,
    Since they are easily accessed by all threads, thus you need to apply any kind of synchronization (via locks, signals, mutex, etc).
    Mutex:https://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx
    Thread signaling basics:http://stackoverflow.com/questions/2696052/thread-signaling-basics
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Neccessity of Public Static.

    My Warm Hello to Everyone Out there,
    I am absolutely New to Java. Absolutely. I am astonished by the pure beautiful advances made to the paradigm of C++, that created this enormous Programming language.
    Well I understand for the Most common example: "Example.java" Program that one may find in most of the books, as the starting program for the Life in Java...
    class Example{
        public static void main(string args[]){
            // body of main
    }In Which "Example". can this main() be anything else: private or protected?
    If no Why not?
    :: DreamyDinesh ::

    It seems that Java's Initial Versions might have been doing something else. It looks as if either, this
    method of sandwitching the main() inside a Class (whose nomenclature, is not 2 b ignored) was followed
    out of experience or it was well planned then, brought into action.It was ever thus. The JLS (Java Language Specification) has always specififed that a program's main
    is to be public and static, but some earlier versions of Sun's JVM didn't check for that public modifier,
    so one could thrill to having their private mains executed. The current JVMs do check for this.

  • Problem to override a public static variable

    Hello,
    I have a problem when trying to override a public static value.
    Here is my example.
    I have one class defining var szName
    public class myClass1 {
    public static String szName = "First Name";
    And an extention
    public class myClass2 extends myClass1{
    public static String szName = "F. N.";
    In my main class if I do:
    myClass2 myObject = new myClass2();
    System.out.println("szName = " + myObject.szName);
    I get "szName = First Name" instead of "szName = F. N."
    Can somebody explain me what is wrong?
    Thanks in advance.
    Alain.

    You can only override non-private, non-static, methods. Other stuff may be hidden or shadowed, but not overridden.
    For anthing other than a non-private, non-static method, it's the compile-time type of the reference, not the runtime class of the object, that determines which class' version gets used.
    The code you provided prints F.N, not First Name as you state. I assume you meant this line myClass2 myObject = new myClass2();to look like this
    myClass1 myObject = new myClass2();If you had done that, then you'd have seen First Name, becuase myClass1 is of type myObjecdt1, and the compiler doesn't even see what's on the RHS of equals for this.

  • How can i pass the values to method public static void showBoard(boolean[][

    I need x and y to pass to the method
    public static void showBoard(boolean[][] board
    i am very confused as to why its boolean,i know its an array but does that mean values ar true or false only?Thanks
    import java.util.Random;
    import java.util.Scanner;
    public class Life1
         public static void main(String[] args)
              int x=0;
              int y=0;
              Scanner keyIn = new Scanner(System.in);
              System.out.println("Enter the first dimension of the board : ");
              x = keyIn.nextInt();
              System.out.println("Enter the second dimension of the board : );
              y = keyIn.nextInt();
              boolean[][] board = new boolean[x][y];
              fillBoard(board);
              showBoard(board);
              //Ask the user how many generations to show.
              board = newBoard(board);
              showBoard(board);
         //This method randomly populates rows 5-9 of the board
         //Rewrite this method to allow the user to populate the board by entering the
         //coordinates of the live cells.  If the user requests that cell 1, 1 be alive,
         //your program should make cell 0,0 alive.
         public static void fillBoard(boolean[][] board)
              int row, col, isAlive;
              Random picker = new Random();
              for(row = 4; row < 9; row++)
                   for(col = 4; col < 9; col++)
                        if (picker.nextInt(2) == 0)
                          board[row][col] = false;
                        else
                          board[row][col] = true;
         //This method displays the board
         public static void showBoard(boolean[][] board)
              int row, col;
              System.out.println();
              for(row=0; row < x; row++)
                   for(col=0; col<y; col++)
                        if (board[row][col])
                             System.out.print("X");
                        else
                             System.out.print(".");
                   System.out.println();
              System.out.println();
         //This method creates the next generation and returns the new population
         public static boolean[][] newBoard(boolean[][] board)
              int row;
              int col;
              int neighbors;
              boolean[][] newBoard = new boolean[board.length][board[0].length];
              makeDead(newBoard);
              for(row = 1; row < board.length-1; row++)
                   for(col = 1; col < board[row].length-1; col++)
                        neighbors = countNeighbors(row, col, board);
                        //make this work with one less if
                        if (neighbors < 2)
                             newBoard[row][col]=false;
                        else if (neighbors > 3)
                             newBoard[row][col] = false;
                        else if (neighbors == 2)
                             newBoard[row][col]= board[row][col];
                        else
                             newBoard[row][col] = true;
              return newBoard;
         //This method counts the number of neighbors surrounding a cell.
         //It is given the current cell coordinates and the board
         public static int countNeighbors(int thisRow, int thisCol, boolean[][] board)
              int count = 0;
              int row, col;
              for (row = thisRow - 1; row < thisRow + 2; row++)
                   for(col = thisCol - 1; col < thisCol + 2; col++)
                     if (board[row][col])
                          count++;
              if (board[thisRow][thisCol])
                   count--;
              return count;
         //This method makes each cell in a board "dead."
         public static void makeDead(boolean[][] board)
              int row, col;
              for(row = 0; row < board.length; row++)
                   for(col = 0; col < board[row].length; col++)
                        board[row][col] = false;
    }

    this is what im workin with mabey you can point me in the right directionimport java.util.Random;
    /* This class creates an application to simulate John Conway's Life game.
    * Output is sent to the System.out object.
    * The rules for the Life game are as follows...
    * Your final version of the program should explain the game and its use
    * to the user.
    public class Life
         public static void main(String[] args)
              //Allow the user to specify the board size
              boolean[][] board = new boolean[10][10];
              fillBoard(board);
              showBoard(board);
              //Ask the user how many generations to show.
              board = newBoard(board);
              showBoard(board);
         //This method randomly populates rows 5-9 of the board
         //Rewrite this method to allow the user to populate the board by entering the
         //coordinates of the live cells.  If the user requests that cell 1, 1 be alive,
         //your program should make cell 0,0 alive.
         public static void fillBoard(boolean[][] board)
              int row, col, isAlive;
              Random picker = new Random();
              for(row = 4; row < 9; row++)
                   for(col = 4; col < 9; col++)
                        if (picker.nextInt(2) == 0)
                          board[row][col] = false;
                        else
                          board[row][col] = true;
         //This method displays the board
         public static void showBoard(boolean[][] board)
              int row, col;
              System.out.println();
              for(row=0; row < 10; row++)
                   for(col=0; col<10; col++)
                        if (board[row][col])
                             System.out.print("X");
                        else
                             System.out.print(".");
                   System.out.println();
              System.out.println();
         //This method creates the next generation and returns the new population
         public static boolean[][] newBoard(boolean[][] board)
              int row;
              int col;
              int neighbors;
              boolean[][] newBoard = new boolean[board.length][board[0].length];
              makeDead(newBoard);
              for(row = 1; row < board.length-1; row++)
                   for(col = 1; col < board[row].length-1; col++)
                        neighbors = countNeighbors(row, col, board);
                        //make this work with one less if
                        if (neighbors < 2)
                             newBoard[row][col]=false;
                        else if (neighbors > 3)
                             newBoard[row][col] = false;
                        else if (neighbors == 2)
                             newBoard[row][col]= board[row][col];
                        else
                             newBoard[row][col] = true;
              return newBoard;
         //This method counts the number of neighbors surrounding a cell.
         //It is given the current cell coordinates and the board
         public static int countNeighbors(int thisRow, int thisCol, boolean[][] board)
              int count = 0;
              int row, col;
              for (row = thisRow - 1; row < thisRow + 2; row++)
                   for(col = thisCol - 1; col < thisCol + 2; col++)
                     if (board[row][col])
                          count++;
              if (board[thisRow][thisCol])
                   count--;
              return count;
         //This method makes each cell in a board "dead."
         public static void makeDead(boolean[][] board)
              int row, col;
              for(row = 0; row < board.length; row++)
                   for(col = 0; col < board[row].length; col++)
                        board[row][col] = false;
    }

  • Declaring public static final variables in jsp?

    The question is in the title...
    I know this is not a jsp forum, but some people here might know if it's possible or not.
    If yes, how to declare them and how to access them from other jsp pages?
    Thx

    If you need that, you definitely do too much work in your JSPs. You should do all your work in Servlets (or Actions if you're using Struts or something similar).
    Your JSPs should only do the presentation.
    Remember that JSPs are not classes (they are compiled into classes internally, but you don't have direct access to those).
    If you absolutely need such a public static final field that you want to access from several JSPs, just define it in a Class and reference that class from your JSPs.

  • JDev 3.2 Deployment wizard failed to show public static methods in step #3.

    JDeveloper 3.2 and 3.1 Deployment Wizard ( step #3) does not show any public static methods being deployed as Java stored procedures. The "settings" button is disabled.
    Is this a demo version of the tool ?

    It's probably easier to add them all and remove the ones you don't want. Admittedly this is a bit cumbersome, because the 3.2 navigator doesn't allow multiple selection..
    (one area that's much better in 9i :) )
    Brian

  • Why ..we have to use this ? public static void ? please !

    hi ...im ibrahim ..and im new here in java nd new in the forum too ...nd please i would like to know ...why
    do we use the method
    public static void main (String []args)
    i mean why ..static nd why public ..why void ....why main ..nd why (string []args)
    ...why we use it ...always ....hopefully ..im looking for a very clear answer to this ...issue ..?
    please help .......!

    public - this is the visibility modifier (it means that the body method can be call by any outside method)
    static - the method is a static instance of the class. Not sure what exactly it does though.
    void - this is the return type. void means that the method returns nothing.
    main - the name of the method. It can be anything.
    "public static void main" - this is the main method where upon executing the Java program the Java Virtual Machine will try to locate this method within the specifies class to be executed. This is always the first one to run when executing a Java program. None of this word may be changed or the program cannot be run.

  • Can you override a public static method?

    Can you override a public static method?

    A static method belongs to a class, not to a particular object, because you can call them without having an object instantiated. Methods are over rided which are inherited from an object. Since Static methods (although inherited) are not bound to a particular object, are not overridden.
    Though you have a method in the subclass with the same signatures but if you try to call super.____() you will get the error
    non-static variable super cannot be referenced from a static context

  • Trying to acces the value of a public static final int using reflection

    -Java 6
    -Windows XP
    -Signed Applet
    doing the following:
    Class.forName(classname).getField(code).getInt(null);
    is giving me the error:
    java.lang.IllegalAccessException: Class com.cc.applet.util.ServiceConfiguration can not access a member of class com.cc.util.error.codes.SendMessageErrorCodes with modifiers "public static final"
         at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
         at java.lang.reflect.Field.doSecurityCheck(Unknown Source)
         at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
         at java.lang.reflect.Field.getInt(Unknown Source)
    I'm not understanding why it can't access the value of the field. Any help would be great.
    Edited by: zparticle on Oct 17, 2007 11:07 PM

    stefan.schulz wrote:
    oebert, you are right. Good one.
    I actually think that, in this case, the message is misleading. The current implementation of sun.reflect.Reflection.ensureMemberAccess() treats any failing access check the same. It should and could inculde better contextual information.Stefan,
    That is a good point. Did you file a RFE with Sun yet? I also think they should provide a more contextual error message in this case.
    Gili

Maybe you are looking for