Meaning of  "int ...j"

Hi,
I am preparing for Java certification, I came across a method
declaration in a mock question.
public void methodX(int i, int... j)
Can anybody explain the meaning of "int... j"?
Thanks.

The second argument is a varargs argument, meaning it can be a variable number of arguments, all ints. Basically, when calling that method, you have to provide the first argument, but can provide either 0 or more ints for the second one, or even an array of ints. eg
methodX(1);
methodX(1, 2);
methodX(1, 2, 3, 4, 5, 6, 7, 8, 9);
methodX(1, new int[] { 2, 3, 4, 5, 6, 7 });are all valid ways to call that method. The varargs portion (with the '...') must all be of the same type, and internal to that method, it will appear to be an array

Similar Messages

  • Method using int array as parameter

    Hi everyone!!
    I wonder what I'm doing wrong in this little piece of code
    Why can't I reach the return x[2];Anyone who can answer me??
    public class ArrayTest
         public static void main(String [] args)
              int [] y = {5};
              arrayTest(y);
         static int arrayTest(int [] x)//I guess I have sent y to this parameter now right?
              if(x.length<3)//So why is it that this if statement is true when x.length definitely
              {            //is greater than 3
                   System.out.println("Short Array");
                   return (0);
              return x[2];//why don't I reach here????

    public class ArrayTest
         public static void main(String [] args)
              int [] y = {5};
              arrayTest(y);
    static int arrayTest(int [] x)//I guess I have sent y
    to this parameter now right?
    if(x.length<3)//So why is it that this if statement
    t is true when x.length definitely
              {            //is greater than 3
                   System.out.println("Short Array");
                   return (0);
              return x[2];//why don't I reach here????
    }Hi!
    I haven't tried the code but it seems like you haven't got anything to return to. I mean, try
    int k = arrayTest(y);
    and another thing it might possibly be is that you have a blank space between "int" and "[]" but its probably not it.
    Sincerely//
    Andreas

  • Dont understand EXT. and INT.  ETC.

    Hi im new to the program and like to animated so i thought to write a film script. But i dont really know what all the short elements means like INT. for example.
    Can somebody please give me a link or an explonation to all this short cuts.
    Thanks!

    Hi,
    First line of a scene in a screenplay is know as slug line.
    Please refer this wiki article for more info:
    http://en.wikipedia.org/wiki/Screenplay_slug_line
    Thanks
    Rohit
    Adobe Story Team

  • How to pass a variable from one class to another class?

    Hi,
    Is it possible to pass a variable from one class to another? For e.g., I need the value of int a for calculation purpose in method doB() but I get an error <identifier> expected. What does the error mean? I know, it's a very, very simple question but once I learn this, I promise to remember it forever. Thank you.
    class A {
      int a;
      int doA() {
          a = a + 1;
          return a;
    class B {
      int b;
      A r = new A();
      r.a;  // error: <identifier> expected. What does that mean ?
      int doB() {
         int c = b/a;  // error: operator / cannot be applied to a
    }Thank you!

    elaine_g wrote:
    I am wondering why does (r.a) give an error outside the method? What's the reason it only works when used inside the (b/r.a) maths function? This is illegal syntax:
    class B {
      int b;
      A r = new A();
      r.a;  //syntax error
    }Why? Class definition restricts what you can define within a class to a few things:
    class X {
        Y y = new Y(); //defining a field -- okay
        public X() { //defining a constructor -- okay
        void f() { //defining a method -- okay
    }... and a few other things, but you can't just write "r.a" there. It also makes no sense -- that expression by itself just accesses a field and does nothing with it -- why bother?
    This is also illegal syntax:
    int doB() {
          A r = new A();
          r.a;  // error: not a statement
    }Again, all "r.a" does on its own is access a field and do nothing with it -- a "noop". Since it has no effect, writing this indicates confusion on the part of the coder, so it classified as a syntax error. There is no reason to write that.

  • F4 help issue

    Hi all,
    I have requirement in providing f4 help for a field.
    I want similiar to search help where i can input few values and get the required values based on the input.
    Input few values means inputing int he pop up window when we press f4 values.
    I can use search help in here because the value for which i am providing search help has duplicate records so i cannot elimnate right.
    Please let me how to write code for this.
    I WANT SOMETHING SIMILAR TO WHAT WE GET WHEN WE USE DIALOG WITH VALUE RESTRICTION OPTION WHILE CREATING SEARCH HELP.
    Thanks

    Hi Deepthi,
    Check out the links.
    http://help.sap.com/saphelp_nw04s/helpdata/en/c9/83eb02be4c11d1950200a0c929b3c3/content.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/cf/21ee93446011d189700000e8322d00/content.htm
    reward points if this helps.
    Manish
    Message was edited by: Manish Kumar

  • How to create an Average Image from Gray Scale (8 bits) JPEG Images

    I�m trying to create a mean image from 9 JPEG Images, but this mean image has lots of "noise", is distorced, and doesnt�resemble at all the original ones.
    I need this mean image so I�ll correlate each of the original ones to find out the best image I�m going to choose ussing NCC (normalized cross correlation coeficient).
    When I use setRGB(x,y,rgb), it returns diferent "images" according to the number of zeros, for ex.: rgb = 028028028 is different from 28028028 and from 282828. I can�t find a way to work it out.
    My algorithm is the folowing:
            File f;
            double [] [] pixels = null;
            Color [] [] tempPixel = null;
            Integer [] [] byte0 = null;
            Integer [] [] byte1 = null;
            Integer [] [] byte2 = null;
            Integer [] [] byte3 = null;
         Integer [] [] tempPixels = null;
            mean = null;
            int w,h;
            fileNames = new String[numFrames];
            for (int i=1; i<numFrames; i++){
                fileName = path + "Frame#" + i + ".jpg";
                fileNames[i-1] = fileName;
            // just for getting width, height, for configuring pixels array and
            // buffered images - mean & best.
            fileName = path + "Frame#8.jpg";
            f= new File(fileName);
            try{
                temp = ImageIO.read(f);
            }catch(IOException io){ return false;}
            w = temp.getWidth();
            h = temp.getHeight();
            mean = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
         pixels = new double [w][h];
            byte0 = new Integer [w][h];
            byte1 = new Integer [w][h];
            byte2 = new Integer [w][h];
            byte3 = new Integer [w][h];
            tempPixel = new Color[w][h];
              tempPixels = new Integer[w][h];
            f=null; temp = null;
            //reset pixels values.
            for(int x = 0; x < w; x++){
                for(int y = 0; y < h; y++){
                    byte0[x][y] =0;
                    byte1[x][y]=0;
                    byte2[x][y]=0;
                    byte3[x][y] = 0;
                    pixels[x][y] = 0;
            // read each file (image), and according to W & H and collects the
            // pixels values.
            for(int j=0; j<numFrames-1; j++) {
                f = new File(fileNames[j]);
                try{
                    temp = ImageIO.read(f);
                }catch(IOException io){ return false;}
                if(temp!=null)
                    for(int x=0 ; x< temp.getWidth(); x++){
                    for(int y=0; y<temp.getHeight(); y++){
                        tempPixel[x][y] = new Color(temp.getRGB(x,y));
                  pixels[x][y] = pixels[x][y] + temp.getRGB(x,y) / 16581375;
                        //BLUE
                        byte0[x][y] = byte0[x][y] + (tempPixel[x][y].getBlue());//tempPixel[x][y].getBlue(); //& 0xff;
                        //GREEN
                        byte1[x][y] = byte1[x][y] + (tempPixel[x][y].getGreen());// >>8 & 0xff;
                        //RED
                        byte2[x][y] = byte2[x][y] + (tempPixel[x][y].getRed()); //>>16 & 0xff;
                        //ALPHA
                        byte3[x][y] = byte3[x][y] + (tempPixel[x][y].getAlpha()); //>>24 & 0xff;
                f=null;
            }//end of loop for j<numFrames
            String t0, t1, t2, t3;
            for(int x=0 ; x< temp.getWidth(); x++){
                for(int y=0; y< temp.getHeight(); y++){
                     byte0[x][y] = byte0[x][y] / numFrames;
                    if((byte0[x][y])<10)
                             t0= "0" + byte0[x][y].toString();
                    //else if((byte0[x][y])>=10 & ((byte0[x][y])<100))
                    //    t0 = "0" + byte0[x][y].toString();
                    else
                        t0 = byte0[x][y].toString();
                    byte1[x][y] = byte1[x][y] / numFrames;
                    if((byte1[x][y])<10)
                             t1=  "0" + byte1[x][y].toString();
                    //else if((byte1[x][y])>=10 & ((byte1[x][y])<100))
                    //    t1= "0" + byte1[x][y].toString();
                    else
                        t1 = byte1[x][y].toString();
                    byte2[x][y] = byte2[x][y] / numFrames;
                    if((byte2[x][y])<10)
                             t2= "0" + byte2[x][y].toString();
                    //else if((byte2[x][y])>=10 & ((byte2[x][y])<100))
                    //    t2 = "0" + byte2[x][y].toString();
                    else
                        t2 = byte2[x][y].toString();
                    byte3[x][y] = byte3[x][y] / numFrames;
                    if((byte1[x][y])<10)
                        t3="0" + byte3[x][y].toString();
                    else
                        t3 = byte3[x][y].toString();
                        pixels[x][y] = (pixels[x][y]/numFrames) * 16581375;
                    try{
                        String rgbs = t2+t1+t0;
                        Integer rgb = Integer.valueOf(rgbs);
                              //System.out.println("Valor do rgb: " +rgb);
                        mean.setRGB(x,y,(int)pixels[x][y]);
                    }catch(NumberFormatException nfe){
                        System.out.println("ERROR: Integer to STRING: "  + nfe);
                        return false;
                    }// end of catch

    It�s ok, I�ve already found the solution.
    Thanks.

  • Looping over an array avoiding scriptlets

    Hello,
    I want to loop over an array avoiding java scriptlets. Here is the code I would like to "clean".
    <%
    int rowCol=0;
    for(int i=0; i<countryArray.length; i++){
    rowCol++;
    Country country = (Country)countryArray;
    out.println("<tr " + ((rowCol%2==0)?("class=\"evenRow\""):("class=\"oddRow\"")) + ">");
    out.println("<td class=\"countryName\">" country.getName() "</td>");
    out.println("<td class=\"countryCapital\">" country.getCapital() "</td>");
    out.println("<td class=\"number\">" + country.getFormattedLandArea() + "</td>");
    out.println("<td class=\"number\">" country.getFormattedPopulation() "</td>");
    out.println("<td class=\"number\">" country.getFormattedGdp() "</td>");
    out.println("<td class=\"number\">" country.getFormattedGdp_per_head() "</td>");
    out.println("<td><a class=\"more\" href=\"pais.jsp?countryID=" + country.getId() + "\">m?s...</a></td>");
    out.println("</tr>");
    %>
    Can anyone give me some guidelines please?
    Thanks in advance,
    Julien.

    you mean this:
    <%
    int rowCol=0;
    for(int i=0; i<countryArray.length; i++){
      rowCol++;
      Country country = (Country)countryArray;
    %>
    <tr class="<%= rowCol%2==0? "evenRow" : "oddRow" %>">
    <td class="countryName"><%= country.getName() %></td>
    <td class="countryCapital"><%= country.getCapital() %></td>
    <td class="number"><%= country.getFormattedLandArea() %></td>
    <td class="number"><%= country.getFormattedPopulation() %></td>
    <td class="number"><%= country.getFormattedGdp() %></td>
    <td class="number"><%= country.getFormattedGdp_per_head() %></td>
    <td><a class="more" href="pais.jsp?countryID=<%= country.getId() %>">m?s...</a></td>
    </tr>
    <%
    %>

  • How to write Question paper program in jsp....

    Hi..,
    This is sure from india. I would like to develop online examination project. Everything is ok. But i have a problem at deveop of question paper. I have 10 questions in my database. I would like display those questions one by one. How can i done this job. Please any one guide me. Because, i am new to this concept.
    with regards
    sure..)-

    First you need to extract all the question from database..
    Then put all of those questions in any of collection object...
    Then set this collection object in request as attribute..
    Keep this object in request till all question are not shown(you can eliminate questions after the have been asked)..
    Code might be like this.
    HashMap result = new HashMap();
    connection = .......;
    Statement stmt=connection.createStatement();
    rs = stmt.executeQuery("Your query");
    int count=0;
    while(rs.next())
    count++;
    String question = rs.getString("colName");
    result.put(""+count,question); //( ""+count)>>>>>means converting int to String
    request.setAttribute("questions",result);
    ====================================================
    now in every JSP which is intended to display a question will have to get this result object..
    Lets assume we are about to display first question()....
    ===========================================
    //////// First get result map from request
    HashMap questions = (HashMap)request.getAttribute("questions");
    String count;
    count = request.getAttribute("count");
    if(count==null)
    count="1";
    String question = questions.get(count);
    count = new String(""+(Integer.parseInt(count).intValue()+1));
    ///Now do what you have to do with this questionresult
    questions.remove();
    request.setAttribute("count",count);////setting question no in request
    request.setAttribute("questions",questions);////setting rest of questions in request
    ===================================================
    hope this might be helpful........
    if there is any problem you can consult me anytime

  • Possible loss of precision and santiy

    I'm having a bit of a problem dealing with bitwise operators and the compiler complaining of
    possible losses of precision (although I know there won't be). So I constructed some "do or die" code ;
    public class byteWise {
         public static void main(String[] args) {
              byte a=1;
              byte b=64;
              byte c= a & b;
    and javac produced this reply:
    D:\Java\byteWise.java:5: possible loss of precision
    found : int
    required: byte
              byte c= a & b;
    ^
    1 error
    What does it mean, "found int, expected byte" ? There's no int in the entire source code.
    Please help!

    Possible loss of precision only denotes that a specific mathematical operation you are performing provides a value that of a data type different than that you are storing it into. It is simply type checking that is performed by the compiler. If you want to bypass this, then you need to do an explitic cast of the data type to the type that you are assigning the value.
    Example:
    double bob = 5.5;
    int jack = 3;
    int sue = bob + jack; //Possible loss of precision.
    int sue = (int)(bob + jack) //This tells the compiler I know what I am doing.
    -Jason Thomas

  • Input stream

    Can datainputstream be used to read and write a file?
    I tried to save a file from a URL. But the file isn't read completely. What is my mistake?
         HttpConnection c = (HttpConnection) Connector.open(url); //change here while run
         DataInputStream response = new DataInputStream(c.openDataInputStream());
                           filecon = (FileConnection)
                        Connector.open("file:///C:/Music/"+filename+".amr"); //nokia
                  if(!filecon.exists()) {
                                filecon.create();
                   DataOutputStream output= filecon.openDataOutputStream();
                    int p=response.available();
                    int i=0;
              while(i<p){
                   output.writeByte((int)response.readByte());
                   i++;
              output.close();
                 filecon.close();

    csckid wrote:
    what does this line means?
    int q=response.readInt();It means you don't know what you're doing.
    Just read from the stream until the end. Dunno about j2me's datainputstream, but it'll probably return -1 at the end of the stream.

  • Statement not being reached

    I had this code working earlier but after changing some variable names, only half of it works. Ive tried and tired and I cannont figure out what ive done. Any help would be appreciated. Ive posted a comment tag jsut above where it isnt working. Everything above works fine.
       import java.util.*;
       import java.io.*;
        public class DateMain extends Date
          static Scanner console=new Scanner(System.in);
           public static void main(String[]args)
             int month=0;
             int day=0;
             int year=0;
             int y;
             int x;
             Date myDate=new Date(month,day,year);
             Date otherDate=new Date(00,00,1900);
             System.out.println("Please enter the month, day,and year \n"
                +"in the form month/day/year. Please press enter after each entry");
             month=console.nextInt();
             day=console.nextInt();
             year=console.nextInt();
             System.out.print("The Date is:"+month+"/"+day+"/"+year);
             System.out.println();
             System.out.print("Here is a copy of the date:"+month+"/"+day+"/"+year);
             System.out.println();
             if(year%4==0)
                System.out.println(year+"  Is a leap year.");
             else
                System.out.println(year+"  Is not a leap year.");
            //Stops working here
             if(0<day&&day>=31)
                if(month==1)
                   x=0+day;
                   y=365-day;
                if(month==2)
                   x=31+day;
                   y=334-day;
                   if(month==3)
                      x=60+day;
                      y=275-day;
                   if(month==4)
                      x=91+day;
                      y=244-day;
                   if(month==5)
                      x=122+day;
                      y=214-day;
                   if(month==6)
                      x=153+day;
                      y=183-day;
                   if(month==7)
                      x=183+day;
                      y=153-day;
                   if(month==8)
                      x=214+day;
                      y=122-day;
                   if(month==9)
                      x=244+day;
                      y=92-day;
                   if(month==10)
                      x=275+day;
                      y=61-day;
                   if(month==11)
                      x=305+day;
                      y=31-day;
                   if(month==12)
                      x=336+day;
                      y=0+day;
                   if(year%4==0)
                      System.out.println("There are " +year +" days left in the year.");
                   else
                      System.out.println("There are " +year +"days left in the year.");
                   if(year%4==0)
                      System.out.println(x+ " days have passed this year.");
                   else
                      System.out.println(x+ "days have passed this year.");
       }   Edited by: codyman on Apr 29, 2008 9:30 PM

    Get rid of the single quotes. The case bits are integral values - you can use characters like '1', '2', '3', '*' but in your case you mean simple ints like 1, 2, 3, 666.
    switch(number)
        case 1: // <-- not '1'
            System.out.println("one");
            break;
        case 42:
            /*etc*/
            break;
      }An "unclosed" char literal will occur if you take out the righthand ' but leave the lefthand one in.
    case '1: //<-- compiler will *not* like this

  • 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

  • Queues and Exceptions

    Ok, I have a program that involves queues. Now, when the program checks if a queues is empty, if it is, it is supposed to handle an error. My prof uses "Underflow" , but I keep getting errors that it is undefined. I looked in the API and couldn't find anything in java.lang that says Underflow. What error out of java.lang should I use if the queue is empty?
    Here is some code so you can see what I mean:
    public int getFront() throws underflow
    if (! isEmpty())
    throw new Underflow("Empty queue"); <---------
    return array[front];
    try
    while (! Subqueue0.isEmpty());
    int extract = Subqueue0.dequeue();
    Master.enqueue(extract);
    } catch(Underflow e){} <--------

    You can create your own exceptions in Java like
    public class UnderFlowException extends Exceptionto handle several kinds of faults. Seems like your Prof has done so.

  • Array Qestion # 2

    Finaly got all my other problems sorted out now I have one more ..... it never ends .... I need to get the pre tax price entries and divide them by the final int MAX_ITEMS .... I have no idea on how the method should look ... anyone able to help me out here??
    public class Assignment_5
        private static final int MAX_ITEMS = 3; //Sets final array length
        private static CatalogueItem[] itemList; // sets array
        private static StringTokenizer split;// sets tokenizer to read the input text
        NumberFormat cash = NumberFormat.getCurrencyInstance(new Locale("en","AU"));
        private static void main (String[] args) throws IOException
            String temp1 = ""; // sets String for first item
            String temp2 = ""; // sets String for second item
            double temp3 = 0; // sets Double for third item
            String inString = "";
            int preTotal = 0;
            double minPrice, maxPrice;
            BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
            itemList = new CatalogueItem[MAX_ITEMS]; // sets array length
            System.out.println ("Enter five Items of data:");
            for(int i = 0; i < MAX_ITEMS;i++) // sets the length of the question
                inString = stdin.readLine(); // read the input lines
                // sets the String Tokenizer and the symbols that can be used to seperate the
                // text to be read.
                split = new StringTokenizer (inString, ".,;:/!?()\n\t");
                temp1 = split.nextToken(); // sets the first token to be read
                temp2 = split.nextToken(); // sets the second token to be read
                temp3 = Double.parseDouble (split.nextToken()); // sets the third token to be read
                // create an instance of CatalogueItem element of the array
                itemList[i] = new CatalogueItem(temp1, temp2, temp3);
            } // end of for loop
                System.out.println();
                System.out.println ();
                System.out.println("LISTING OF ALL GOODS");
                System.out.println();
                System.out.println("Cat \tDesciption \tEx Tax \tTax \tInc Tax");
                System.out.println ();
                System.out.println("--- \t---------- \t------ \t--- \t--------");
                System.out.println();
                for(int i = 0;i <= MAX_ITEMS -1;i++)
                    System.out.println(itemList.getCatCode() + "\t" + itemList[i].getDesc()
    + "\t\t" + itemList[i].getPrice() + "\t" + itemList[i].getTaxAmount()
    +" \t" + itemList[i].getTaxIncl());
    System.out.println ();
    System.out.println ();
    System.out.println ("CHEAPEST GOODS IN CATALOGUE");
    System.out.println ();
    minPrice = cheapest(itemList, MAX_ITEMS);
    System.out.println("Cat \tDesciption \tEx Tax \tTax \tInc Tax");
    System.out.println ();
    System.out.println("--- \t---------- \t------ \t--- \t--------");
    System.out.println();
    for(int i = 0;i < MAX_ITEMS;i++)
    if(itemList[i].getTaxIncl() == minPrice)
    System.out.println(itemList[i].getCatCode() + "\t" + itemList[i].getDesc()
    + "\t\t" + itemList[i].getPrice() + "\t" + itemList[i].getTaxAmount()
    +" \t" + itemList[i].getTaxIncl());
    System.out.println ();
    System.out.println ();
    System.out.println ("MOST EXPENSIVE GOODS IN CATALOGUE");
    System.out.println ();
    maxPrice = expensive (itemList, MAX_ITEMS);
    System.out.println("Cat \tDesciption \tEx Tax \tTax \tInc Tax");
    System.out.println ();
    System.out.println("--- \t---------- \t------ \t--- \t--------");
    System.out.println();
    for(int i = 0;i < MAX_ITEMS;i++)
    if(itemList[i].getTaxIncl() == maxPrice)
    System.out.println(itemList[i].getCatCode() + "\t" + itemList[i].getDesc()
    + "\t\t" + itemList[i].getPrice() + "\t" + itemList[i].getTaxAmount()
    +" \t" + itemList[i].getTaxIncl());
    public static double cheapest (CatalogueItem[] itemList,int size)
    double minPrice = itemList[0].getTaxIncl();
    for(int i =1; i < size; i++)
    if(itemList[i].getTaxIncl() < minPrice)
    minPrice = itemList[i].getTaxIncl();
    return minPrice;
    public static double expensive (CatalogueItem[] itemList, int size)
    double maxPrice = itemList[0].getTaxIncl();
    for (int i = 1; i < size;i++)
    if (itemList[i].getTaxIncl() > maxPrice)
    maxPrice = itemList[i].getTaxIncl();
    return maxPrice;

    Is this what you mean:
    public int preTaxWorth(CatalogueItem[] itemList) {
         // Add all array items together
         int sum = 0;
         for (int i = 0; i < itemList.length ; sum++ ) {
              sum = sum + intemList;
         // Divide it by MAX_ITEMS
         int finalResult = sum / MAX_ITEMS;
         // Return it
         return finalResult;
    Getting it to this stage gets me this error message.  operator + cannot be applied to int, CatalogueItem
    One question I do have is how am I calling the getPrice constructior from the CatalogueItem class?
    Here is the code as I am seeing it.public int preTaxWorth(CatalogueItem[] itemList)
    { // Add all array items together
    int sum = 0;
    for (int i = 0;i < itemList.length ; sum++ )
    sum = sum + itemList;
    // Divide it by MAX_ITEMS
    int finalResult = sum / MAX_ITEMS;
    // Return it
    return finalResult;

  • Sql exception : Driver doesnot support this funtion

    I have successfully connected to SQL SERVER 2000 & i was able to retrive data from datbase using SELECT query(using executeQuery),
    but when i do insertion i get SQLException : Driver does not support this function
    Any one know the reason or a solution to it.
    My code is
    String str="INSERT INTO course (co_name,co_duration,co_fee,total_seat,co_detail,available_seat)VALUES (?,?,?,?,?,?)";
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con=DriverManager.getConnection("jdbc:odbc:test2","sa","sa");
    PreparedStatement aCourseStmt=con.prepareStatement(str);
    aCourseStmt.setString(1,coName);
    aCourseStmt.setString(2,coDuration);
    aCourseStmt.setString(3,coFee);
    aCourseStmt.setString(4,totalSeat);
    aCourseStmt.setString(5,coDetail);
    aCourseStmt.setString(6,totalSeat);
    boolean rs=aCourseStmt.execute(str); //i tried executeUpdate also bt not working

    JavaStudentGroup-Mashhur wrote:
    Driver supports it but please pay attention to the type of you information, I mean string, int columns!Obviously not when the SQLException raised explicitly states it isn't.
    The error had nothing to do with the SQL itself. It had to with the fact that he was attempting to use the "execute(String)" method signature on a PreparedStatement object, and that is not supported (at least not in that driver or in any other, that I am aware of).

Maybe you are looking for