Help! Array of polygons

I'm trying to figure out a program for my computer science class. In short, I'm trying to use a bunch of values as points for a polygon (which by itself works just fine, it's the array that messes up) and, in a loop, create multiple instances of the polygon a given distance away.
Polygon polyx[]=new Polygon[50];
     for(int temp=0; temp<10; temp++){
polyx[temp].addPoint( xValues[0]+10*temp, yValues[0]+60*temp );
polyx[temp].addPoint( xValues[1]+10*temp, yValues[1]+60*temp );
polyx[temp].addPoint( xValues[2]+10*temp, yValues[2]+60*temp );
polyx[temp].addPoint( xValues[3]+10*temp, yValues[3]+60*temp );
polyx[temp].addPoint( xValues[4]+10*temp, yValues[4]+60*temp );
polyx[temp].addPoint( xValues[5]+10*temp, yValues[5]+60*temp );
g.drawPolygon( polyx[temp] );
g.fillPolygon(polyx[temp]);
I don't get any errors compiling, but I get runtime errors and It doesn't work.

ok, before jsalonen pulls his/her hair out screaming "do as youre told"
the advice was
"polyx[temp] = new Polygon();"
not
"Polygon polyx[temp] = new Polygon;"
this line should appear as the first line inside the temp for loop
it is needed because declaring an array (in your case of Polygon<s>) creates an array of the desired class, but fills it with null values, not the default constructor "new Object()"
also, the error you got was because your line really tries to declare an array of Polygon and has a syntax error, you cant put [temp] at this point, just [] so the compiler expects ] and got t
if you fixed that you would get an error with "new Polygon", the compiler would expect "new Polygon[int size]"
if you did that how ever you would then be declaring yet another polyx array of Polygon<s> for each iteration of the loop and your code would still not function

Similar Messages

  • Need some java help - arrays

    I've been learning java for the past few weeks and I'mstuck with the following question:
    Write a short program to store the input values of a user-specified amount of whole numbers and output them in a multipcation matrix form, with correct formatting.
    For example, the input of of three numbers 1, 2 and 3 would produce the followinf matrix:
    *1 2 3*
    *2 4 6*
    *3 6 9*
    or the input of 4 numbers 3,7, 4 and 9 would produce the following matrix:
    *3 7 4 9*
    *7 49 28 63*
    *4 28 16 36*
    *9 63 36 81*
    whereby the inner numbers in the grid represent the product of the number on the corresponding top row and left most column, i.e 36 = 9 4*
    The user must be initially be allowed to specify how many numbers they wish to enter, followed by the number themselves. You must maked use of an array for this exercise. Ensure the proper formatting rules are adhered to, i.e. that all columns are aligned vertically (right justified). You can assume no input number greater than 100 will be entered.
    I was wondering if someone could help me with this?

    Or better yet:
    [] 3  7  4  9
    3  9 21 12 27
    7 21 49 28 63
    4 12 28 16 36
    9 27 63 36 81which is i am sure what you were after flounder, the formatting for some reason kept moving the top row over to the left.
    P.S. If the OP is still here...here is a bit of a head start.
    public static void main(String[] args) {
           Scanner sc1 = new Scanner(System.in);
           int[] array;
           int x;
           int y;
           System.out.println("How many numbers do you want to enter? ");
           x = sc1.nextInt();
           array = new int[x];
           System.out.println("Please enter your numbers ");
           for (int i=0;i<x;i++){
               y = sc1.nextInt();
               array=y;
    //test printing contents of array
    System.out.println("--------------");
    System.out.println();
    System.out.println("OUTPUT");
    System.out.println();
    System.out.println("--------------");
    for(int j=0;j<array.length;j++){
    System.out.print(array[j]);

  • Please help/Array sorting

    Please , people help.. I am novice in the Java programming and working on the following problem right now.: Using a single-subscripted array need an applet that inputs 5 numbers, each of which betwee 10 and 100, inclusive. As each number is read,display it only if it is not a duplicate of a number already read. Have to provide for the "worst case" in which all 5 numbers are different . Need a smallest possible array to solve this problem.. Please help. Sitting here and can not do anything abt it..Need code..Sincerely A.

    Have you attempted to do anything at all? Why should
    we help you pass a class so that you can be dead
    weight on our development projects later?this is genius! amen.

  • Need help locating a Polygon class that works in double precision

    The title says it all even though a class with floating points would be good too. ty :)

    You could always make your own polygon class that encapsulates
    java.awt.geom.Line2D
    Line2D has float and double implementations

  • Help: array question

    Hi:
    I have a question concerning character arrays?
    Given a string of letters, how would I find the postion of the letter in the array?
    Thanks.

         String arr = "abcdefg";
         char[] charr = arr.toCharArray();
         for(int j = 0 ; j < charr.length; j++) {
          if(charr[j] == 'e') {
           int postion = j;
           System.out.println("The postion of"+" " + charr[postion] + " " + "is in the" +" " + postion + " " + "cell of charr");
        }Is this what you are looking for ???

  • Please help array and tables

    value for my parameterp_yymm :=(1001,1002,:,:,1005,:,:,1008,,:,:,:,:,1101,1102) colon rep as non selected value
    i need to get position of all values like
    1001 -1
    1002 -2
    1102-14
    then my ouput should like this (yynnynnynnnnyy)
    create or replace
    FUNCTION FN_SUB_BEHAVIOUR(P_YYMM IN VARCHAR2)
    RETURN VARCHAR2
    IS
    TYPE TYP_ARR_TEST IS TABLE OF VARCHAR2(1000) INDEX BY VARCHAR2(1000);
    TYPE ELIMINATE_TYP IS TABLE OF VARCHAR2(15);
    V_ELIMINATE ELIMINATE_TYP;
    ARR_LIST APEX_APPLICATION_GLOBAL.VC_ARR2;
    V_LENGTH VARCHAR2(10000);
    LOOP_VALUE VARCHAR2(10000):=1000;
    I VARCHAR2(10000);
    V_LIKE VARCHAR2(10000);
    V_INDX NUMBER(10); v number(5);
    BEGIN
    --ARR_LIST := APEX_UTIL.STRING_TO_TABLE(p_YYMM,',');
    ARR_LIST := APEX_UTIL.STRING_TO_TABLE(P_YYMM,',');
    for i in 1..ARR_LIST.count loop
    if i=1 then
    v_LIKE:= ''''||ARR_LIST(i)||'''';
    else
    V_LIKE:=','||v_LIKE||','||''''||','||ARR_LIST(i)||'''';
    end if;
    V_ELIMINATE :=ELIMINATE_TYP(V_LIKE);
    FOR I IN V_ELIMINATE.FIRST..V_ELIMINATE.LAST
    LOOP
    v:=i;
    -- IF V_ELIMINATE(I)=';' THEN :='0';
    -- ELSE V_ELIMINATE(I):='1'; END IF;
    --END LOOP;
    RETURN v;
    end loop;
    END LOOP;
    END;
    my ouput should like this (yynnynnynnnnyy)
    Edited by: raj on Mar 23, 2011 2:55 AM
    Edited by: raj on Mar 23, 2011 3:20 AM

    don't you just want to do something like this then?
    ARR_LIST := APEX_UTIL.STRING_TO_TABLE(P_YYMM,',');
    for i in 1..ARR_LIST.count loop
      if arr_list(i) in (';', ':', 'o') then v_result :='N';
      else v_result :='Y';
      end if;
      v_outstring := v_outstring || v_result;
    end loop;
    return v_outstring;

  • Problem with simple animation.  Any help greatly appreciated.

    I am trying to make a circle (which is actually an array of polygons in the shape of a circle) change color over time. Basically what the inner loop does is assign each polygon a random color. The desired effect here is for the circle to be assigned a certain array of colors then have swing repaint the component so we can see the change and repeat, resulting in a nice animation of colors changing over time. What ends up happening is the applet only updates after it has done the entire outer loop. So only the last color state of the circle is seen after it has done all the computations. So it goes from the intial color to the end color, without showing the states in between. What can I do for it to repaint for each of the recolorings? The computation is complex enough so it's not as if it displays the colors so fast that you only notice the end state.
    for (int year=0; year<500000; year+=500)
    for (int x=0; x<180; x++)
    polys[x].setColor(generator.nextInt(250),generator.nextInt(250),generator.nextInt(250));
    repaint();
    poly.update(polys);
    }

    I was struggling to find a relevant piece of code to demonstrate how this can be done. I eventually ended up with the ugliest animation ever.import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class AnimationDemo extends JPanel {
         private static final Color[] COLORS = {Color.WHITE, Color.RED, Color.BLUE, Color.YELLOW, Color.BLACK};
         private static int getNextColorIndex(int aColorIndex) {
              return ++aColorIndex % COLORS.length;
         private static class ColoredSquare {
              int theColorIndex;
              Rectangle theRectangle;
              public ColoredSquare(int aColorIndex, Rectangle aRectangle) {
                   theColorIndex = aColorIndex;
                   theRectangle = aRectangle;
         private static class Mozaic extends JComponent implements Runnable {
              private ColoredSquare[] theColoredSquares;
              public Mozaic() {
                   int width = 49;
                   int height = 49;
                   Dimension squareDimension = new Dimension(10, 10);
                   theColoredSquares = new ColoredSquare[width * height];
                   int index = 0;
                   int colorIndex = 0;
                   Point currentPoint;
                   for (int x = 0; x < width; x++) {
                        for (int y = 0; y < height; y++) {
                             currentPoint = new Point(x * squareDimension.width, y * squareDimension.height);
                             theColoredSquares[index] = new ColoredSquare(colorIndex, new Rectangle(currentPoint, squareDimension));
                             index++;
                             colorIndex = getNextColorIndex(colorIndex);
                   setPreferredSize(new Dimension(width * squareDimension.width, height * squareDimension.height));
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2D = (Graphics2D)g;
                   Color tempColor = g2D.getColor();
                   for (int i = 0; i < theColoredSquares.length; i++) {
                        ColoredSquare coloredSquare = theColoredSquares;
                        int colorIndex = getNextColorIndex(coloredSquare.theColorIndex);
                        g2D.setColor(COLORS[colorIndex]);
                        g2D.fill(coloredSquare.theRectangle);
                        coloredSquare.theColorIndex = colorIndex;
                   g2D.setColor(tempColor);
              public void run() {
                   try {
                        for (int year = 0; year < 500000; year += 500) {
                             repaint();
                             Thread.sleep(50);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
         public AnimationDemo() {
              super(new BorderLayout());
              final Mozaic mozaic = new Mozaic();
              add(new JScrollPane(mozaic), BorderLayout.CENTER);
              add(new JButton(new AbstractAction("start animation") {
                   public void actionPerformed(ActionEvent e) {
                        new Thread(mozaic, "Animation Thread").start();
              }), BorderLayout.SOUTH);
         public static void main(String[] args) {
              final JFrame frame = new JFrame("Animation Demo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new AnimationDemo());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(400, 300);
                        frame.show();

  • Null pointer exception with inner class

    Hi everyone,
    I've written an applet that is an animation of a wheel turning. The animation is drawn on a customised JPanel which is an inner class called animateArea. The main class is called Rotary. It runs fine when I run it from JBuilder in the Applet Viewer. However when I try to open the html in internet explorer it gives me null pointer exceptions like the following:
    java.lang.NullPointerException      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2761)      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2722)      
    at Rotary$animateArea.paintComponent(Rotary.java:251)      
    at javax.swing.JComponent.paint(JComponent.java:808)      
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4771)      
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)      
    at javax.swing.JComponent._paintImmediately(JComponent.java:4668)      
    at javax.swing.JComponent.paintImmediately(JComponent.java:4477)      
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)      
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)      
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)      
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:448)      
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)      
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)      
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    Do inner classes have to be compiled seperately or anything?
    Thanks a million for you time,
    CurtinR

    I think that I am using the Java plugin ( Its a computer in college so I'm not certain but I just tried running an applet from the Swing tutorial and it worked)
    Its an image of a rotating wheel and in each sector of the wheel is the name of a person - when you click on the sector it goes red and the email window should come up (that doesn't work yet though). The stop and play buttons stop or start the animation. It is started by default.
    This is the code for the applet:
    import java.applet.*;
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.util.StringTokenizer;
    import java.net.*;
    public class Rotary extends JApplet implements ActionListener, MouseListener
    public boolean rotating;
    private Timer timer;
    private int delay = 1000;
    private AffineTransform transform;
    private JTextArea txtTest; //temp
    private Container c;
    private animateArea wheelPanel;
    private JButton btPlay, btStop;
    private BoxLayout layout;
    private JPanel btPanel;
    public Image wheel;
    public int currentSector;
    public String members[];
    public int [][]coordsX, coordsY; //stores sector no. and x or y coordinates for that point
    final int TOTAL_SECTORS= 48;
    //creates polygon array - each polygon represents a sector on wheel
    public Polygon polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
    polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
    polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
    polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
    polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48;
    public Polygon polySectors[]={polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
                      polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
                      polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
                      polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
                      polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48};
    public void init()
    members = new String[TOTAL_SECTORS];
    coordsX= new int[TOTAL_SECTORS][4];
    coordsY= new int[TOTAL_SECTORS][4];
    currentSector = -1;
    rotating = true;
    transform = new AffineTransform();
    //***********************************Create GUI**************************
    wheelPanel = new animateArea(); //create a canvas where the animation will be displayed
    wheelPanel.setSize(600,580);
    wheelPanel.setBackground(Color.yellow);
    btPanel = new JPanel(); //create a panel for the buttons
    btPanel.setLayout(new BoxLayout(btPanel,BoxLayout.Y_AXIS));
    btPanel.setBackground(Color.blue);
    btPanel.setMaximumSize(new Dimension(30,580));
    btPanel.setMinimumSize(new Dimension(30,580));
    btPlay = new JButton("Play");
    btStop = new JButton("Stop");
    //txtTest = new JTextArea(5,5); //temp
    btPanel.add(btPlay);
    btPanel.add(btStop);
    // btPanel.add(txtTest); //temp
    c = getContentPane();
    layout = new BoxLayout(c,layout.X_AXIS);
    c.setLayout(layout);
    c.add(wheelPanel); //add panel and animate canvas to the applet
    c.add(btPanel);
    wheel = getImage(getDocumentBase(),"rotary2.gif");
    getParameters();
    for(int k = 0; k <TOTAL_SECTORS; k++)
    polySectors[k] = new Polygon();
    for(int n= 0; n<4; n++)
    polySectors[k].addPoint(coordsX[k][n],coordsY[k][n]);
    btPlay.addActionListener(this);
    btStop.addActionListener(this);
    wheelPanel.addMouseListener(this);
    startAnimation();
    public void mouseClicked(MouseEvent e)
    if (rotating == false) //user can only hightlight a sector when wheel is not rotating
    for(int h= 0; h<TOTAL_SECTORS; h++)
    if(polySectors[h].contains(e.getX(),e.getY()))
    currentSector = h;
    wheelPanel.repaint();
    email();
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void email()
    try
    URL rotaryMail = new URL("mailto:[email protected]");
    getAppletContext().showDocument(rotaryMail);
    catch(MalformedURLException mue)
    System.out.println("bad url!");
    public void getParameters()
    StringTokenizer stSector;
    String parCoords;
    for(int i = 0; i <TOTAL_SECTORS; i++)
    {               //put member names in applet parameter list into an array
    members[i] = getParameter("member"+i);
    //separate coordinate string and store coordinates in 2 arrays
    parCoords=getParameter("sector"+i);
    stSector = new StringTokenizer(parCoords, ",");
    for(int j = 0; j<4; j++)
    coordsX[i][j] = Integer.parseInt(stSector.nextToken());
    coordsY[i][j] = Integer.parseInt(stSector.nextToken());
    public void actionPerformed(ActionEvent e)
    wheelPanel.repaint(); //repaint when timer event occurs
    if (e.getActionCommand()=="Stop")
    stopAnimation();
    else if(e.getActionCommand()=="Play")
    startAnimation();
    public void startAnimation()
    if(timer == null)
    timer = new Timer(delay,this);
    timer.start();
    else if(!timer.isRunning())
    timer.restart();
    Thanks so much for your help!

  • Mapviewer and mixed types

    I installed and looked at the sample code of Mapviewer today, everything worked the first time (much improved quality over 9i). However, when I created a map with one of my tables that has more than one geometry type (in this case both points and polygons), it only drew the point features. Is this "normal"? Does MV look at the first returned record and assume that they are all of this type?

    :-0
    It does help when your polygon's coordinates are not getting rounded down to a single point... It's working now - thanks for looking.

  • I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?

    I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
    Attachments:
    try2.txt ‏2 KB
    read_array.vi ‏21 KB

    The problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
    Here are some of your choices to fix your problem.
    1. Change the source file to a tab delimited file. Your VI will then run as is.
    2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
    3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
    Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
    Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does.

  • Desperate HELP with Random Numbes in an Array & Do / While

    Please somebody help, I have been working this problem for over 7 days now and can't get it. I have tried everything from a while to a do while to this and that. I need to have an Array of 8 that when run will produce random numbers for output between 15 to 25. I CAN"T GET IT PLEASE HELP. I am new to JAVA and have done everything I can think of to resolve this. I even have purchased a new book and looked at every site trying to find a solution. PLEASE HELP! Here it is:
    import javax.swing.*;
    public class RandomArray{
    public static void main (String [ ] args) {
    JTextArea outputArea = new JTextArea ( );
    int myArray [ ]; //array declaration
    myArray = new int [ 8 ]; //allocating memory
    String output = "Array values at initializatioon ";
    output += "\nIndex\tValues";
    for ( int i = 0; i < myArray.length; i ++)
    output += "\n" + i + "\t" + myArray [ i ];
    output += "\n\nArray values after assigning values within the range of 15 and 25";
    do {( int i = 0; i <myArray.length; i++)
         while     myArray [ i ] = 15 + (int) (Math.random ( ) * 25);
    output += "\n" + i + "\t" + myArray [ i ];}
    outputArea.setText (output);
    JOptionPane.showMessageDialog (null, outputArea,
    "Array Value before and after",
    JOptionPane.INFORMATION_MESSAGE);
         System.exit ( 0 );
    The output that I need is in two columns one with the initial array 0-7 and the second should be random numbers 15-25. Please help, please

    here you are :
    import javax.swing.*;
    public class RandomArray
    public static void main (String [ ] args)
         JTextArea outputArea = new JTextArea();
         int       myArray [] = new int[8];
         String output = "Array values at initializatioon ";
         output += "\nIndex\tValues";
         for (int i = 0; i < myArray.length; i ++)
              output += "\n" + i + "\t" + myArray [ i ];
         output += "\n\nArray values after assigning values within the range of 15 and 25";
         for (int i = 0; i < myArray.length; i++)
              myArray [ i ] = 15 + (int) (Math.random ( ) * 10);
              output += "\n" + i + "\t" + myArray [ i ];
         outputArea.setText(output);
         JOptionPane.showMessageDialog (null, outputArea,
              "Array Value before and after",
              JOptionPane.INFORMATION_MESSAGE);
         System.exit(0);

  • Need help on returning arrays from C++ to Java

    Hi all, I hava a C++ application that contains a method that will return a float array to Java. I was able to write the Java Code, the JNI code to call the C++ method and compile them successfully. However on calling the native method from Java, the data in the array returned was not what I want. Please look through my code and see what is wrong with it.
    My Java Code:
    public native float[] Statistics(int inputKey); // This is the native method
    public float[] Stats(int k){ //Java method to call the native method so that I can use it in a Bean for a JSP.
    inputKey = k;
    float[] p = new float[4];
    p = Statistics(inputKey);
    return p;
    For this native method, an integer is passed from Java to the native side and the native method will use this integer to generate a float array size of 4 and populate it with data and return it back to Java.
    My JNI code
    extern "C"
    JNIEXPORT jfloatArray JNICALL
    Java_com_jspsmart_upload_FinalWaterMark_Statistics(JNIEnv *env, jobject obj, jint inputKey)
         jfloatArray floatArray = env->NewFloatArray(4); //This creates a new Java floatArray to store the C++ array
         CWatermarker2App p; // This is the C++ class to be used
         jfloat *stats = p.OnWatermarkStatistics(inputKey) // The C++ method returns a float pointer for an array of size 4
         env->SetFloatArrayRegion(floatArray, 0 , 4 , stats); //storing the C++ float array into the Java float Array
         return floatArray; // return the Array to Java
    In this example, I should have the data returned as [4952.0 2529.0 1706.0 33.6] in the array.
    But i am getting junk instead like 2.53E-23, 1.402E-15 etc..
    Is this a type conversion mistake?
    Please help!

    The first thing I notice - probably not the problem - is the line defining p. There is no reason to define this as an array of size 4, because the return from the native method is going to wipe that definition, replacing it with the return value of the native method. Alternatives:
    1. float[] p = null.
    2. float[] p = Statistics(inputKey);
    3. return Statistics(k);

  • Loops and Arrays help

    Hi,
    I'm a freshman in college and new to java. I am completely lost and really need help with a current assignment. Here are the instructions given by my teacher...
    Building on provided code:
    Loops and Arrays
    Tracking Sales
    Files Main.java and Sales.java contain a Java application that prompts for and reads in the sales for each of 5 salespeople in a company. Files Main.java and Sales.java can be found here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Main.java
    and here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Sales.java It then prints out the id and amount of sales for each salesperson and the total sales. Study the code, then compile and run the program to see how it works. Now modify the program as follows:
    1. (1 pts) Compute and print the average sale. (You can compute this directly from the total; no new loop is necessary.)
    2. (2 pts) Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., "Salesperson 3 had the highest sale with $4500." Note that you don't necessarily need another loop for this; you can get it in the same loop where the values are read and the sum is computed.
    3. (2 pts) Do the same for the minimum sale.
    4. (6 pts) After the list, sum, average, max and min have been printed, ask the user to enter a value. Then print the id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number of salespeople whose sales exceeded the value entered.
    5. (2 pts) The salespeople are objecting to having an id of 0-no one wants that designation. Modify your program so that the ids run from 1-5 instead of 0-4. Do not modify the array-just make the information for salesperson 1 reside in array location 0, and so on.
    6. (8 pts) Instead of always reading in 5 sales amounts, allow the user to provide the number of sales people and then create an array that is just the right size. The program can then proceed as before. You should do this two ways:
    1. at the beginning ask the user (via a prompt) for the number of sales people and then create the new array
    2. you should also allow the user to input this as a program argument (which indicates a new Constructor and hence changes to both Main and Sales). You may want to see some notes.
    7. (4 pts) Create javadocs and an object model for the lab
    You should organize your code so that it is easily readable and provides appropriate methods for appropriate tasks. Generally, variables should have local (method) scope if not needed by multiple methods. If many methods need a variable, it should be an Instance Variable so you do not have to pass it around to methods.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this.
    I'm not asking for someone to do this assignment for me...I'm just hoping there is someone out there patient and kind enough to maybe give me a step by step of what to do or how to get started, because I am completely lost from the beginning of #1 in the instructions.
    Any help would be much appreciated! Thank you!
    Message was edited by:
    Scott_010
    Message was edited by:
    Scott_010

    First ask the person who gave this asignment as to why do you require two classes for this , you can have only the Sales.java class with main method in it . Anyways.
    Let Main.java have a main method which instanciates a public class Sales and calls a method named say readVal() in Sales class.
    In the readVal method of sales class define two arrays i.e ids and sales. Start prompting the user for inputting the id and sales and with user inputting values keep storing it in the respective arrays .. Limit this reading to just 5 i.e only 5 salesPerson.
    Once both the arrays are populated, call another method of Sales class which will be used for all computations and output passing both the arrays.
    In this new method say Compute() , read values from array and keep calculating total,average and whatever you want by adding steps in just this loop. You can do this in readval method too after reading the values but lets keep the calculation part seperate from input.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this. I think this is ur personal stuff , but if you want to use web page , you probably will require to use servlet to read values from the html form passed to the server.

  • Arrays or Spreadshee​ts? Help with School Excercise

    Hello there, my Control Systems Engineering professor will make us a LabView test in a couple of weeks, although he won't actually teach us the software, but rather we need to get our hands dirty. Anyways, I'm trying to resolve this excercise:
    Problem Definition.
    On a storage area of a container terminal containers are stored temporarily waiting for further transportation. The location of a specific container along with its code is stored in a database. Whenever the operator types in the code of a container, the according location is shown on the screen.
    Demands.
    - Take as storing area a rectangle of 3 rows of 4 positions horizontal and 2 positions vertical (24 containers).
    - Each containers is identified by a unique alphanumerical code of 11 digits. Digit # 11 is the check digit, being the last digit of the sum of the previous 10 digits based upon the ASCII table.
    - When filling the database, the user myst apply the code of the container and its location.
    - When searching for a container, the operator applies only the code of the container. On the front panel the according location must be displayed by the program.
    - If a container is not found it must be reported by means of an error message.
    - If an incorrect container code is inserted it must be reported by means of an error message.
    What I've done so far:
    I've made a UI and code so that I can type a 11 digit string and the VI will indicate me if its a valid code or not, based in the comparison of the 11th digit.
    What I need:
    Next step, I believe, is that if the code is valid, I should store it in a database along its position. I know that there is a Database toolkit for LabView, but you must agree it is impractical as this is just an excercise. I was thinking about making an array or a spreadsheet, but have no experience with it. Also it seems that arrays work best with For and While Loops, but I might be wrong... and how can the user assign its position?
    Well, thanks all in advance for ANY suggestions. Everything is welcome.
    Pohl.

    Hello,
    Take a look at the following link:
    http://zone.ni.com/reference/en-XX/help/371361B-01​/lverror/too_few_format_specifiers/
    it explains this error and also gives a link to the format you should use for this function.
    Regards,
    RikP - National Instruments Applications Engineering
    Rik Prins, CLD
    Applications Engineering Specialist Northern Europe, National Instruments
    Please tip your answer providers with kudos.
    Any attached Code is provided As Is. It has not been tested or validated as a product, for use in a deployed application or system,
    or for use in hazardous environments. You assume all risks for use of the Code and use of the Code is subject
    to the Sample Code License Terms which can be found at: http://ni.com/samplecodelicense

  • Help with parallel arrays of different data types

    Hello all, I am having an issue with parallel arrays. My program requires me to read information from a text file into 4 parallel arrays (2 String and 2 double). My text file needs to look something like this:
    John Johnson
    0000004738294961
    502.67
    1000.000
    Jane Smith
    0000005296847913
    284.51
    1000.000
    ...and so on
    Where the first thing is the name (obviously), an account number, the balance in the account, and the credit limit. I just cant figure out how to read everything into the arrays. We havent learned anything too heavy, and this seems a little too advanced for my class, but I guess we will manage. Any help will be appreciated. Thanks guys.
    Casey

    Man this is a dumb homework assignment. The requirements scream out for a class along the lines of
    public class Account{
      private String name, number;
      private double balance,creditlimit;
       // more code here
    }and then to use a List of Account objects.
    Anyway what's your actual problem. There's nothing very hard about it. A loop. So....
    You should consider posting (formatted) code showing what you have done and where exactly you are stuck.

Maybe you are looking for

  • How do i apply a background track to some slides

    I want to add a background track to my project but dont want it to play on the first slide. How do i do that?

  • Where can I buy a new logic board for my iphone 4s

    I phoned apple today and exxplained that I tried to fix my battery connector myself and messed it up I asked if I could buy another motherboard for my iphone 4s to be told apple dont sell parts and to try on ebay I have already tried on ebay and boug

  • I canu00B4t start SAP

    Hi All, I have a problem when a try to start the SAP instance. Iu00B4m running Windows 2000 / MS-SQL Enterprise Server 2000 / SAP R/3 4.7 IDES I check R3trans -d and all fine, i can see the DB. But, in MMC, when i try to up SAP, all disp+work start,

  • Deploying into a video management system

    Flash Interactive Media Server seems to be an amazing product, but is it all just hype? I see plenty of tutorials and scenarios on how to grab the video from a flash player and stream it. But would I would like to see are content management systems t

  • WSUS Metadata Export Error

    Running WSUS 3.0 SP2, using Windows Internal Database. OS is Server 2008 R2. I experienced the null .cab file issue. I applied KB2828185. Upon reboot and running wsusutil.exe export 'name'.cab 'name'.log, a general error is produced "<ExportError Mes