Implementing Arrays

Hi,
I am an novice Java programmer and i am having some trouble with arrays, I have written a program that calculates grades, but it does not use arrays. I would like to use arays in my program and at the same time have it support up to 50 people. Please help me in this matter, thanks,
Martin
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class GradeWatch9{//start of class definition GradeWatch
     public static void main ( String args[] ) {//start of main method
          //string declarations
          String firstname;
          String secondname;
          String studentid;
          String midtermgrade;
          String finalgrade;
          String listings="";
          String option;//variable used to receive user's option <-1>//<0>
          //character declarations
          char actualgrade;//letter grade assigned to total points earned
          char lettergrade=0;//assignment of a letter grade
          //integer declarations
          int loop=0;//(this will be converted fr. option//will compare result)
          int studentid_int;
          int midterm_grade=0;
          int final_grade=0;
          double midterm_gradevalue=0;//point calculations
          double final_gradevalue=0;//point calculations
          double total_gradevalue=0;//total points possible out of 100
          do
          //input dialogs (5) with validations
          boolean firstnamecheck=false;
          firstname = JOptionPane.showInputDialog("Enter The Student's First Name: ");
          for ( int j=0; j<firstname.length(); j++ )
               if(!Character.isLetter(firstname.charAt(j)))
                    firstnamecheck=false;
                    firstname=JOptionPane.showInputDialog("Invalid Entry: \n You have entered an integer. \nPlease Re-enter Sudent's first name: ");
          boolean secondnamecheck=false;
          secondname = JOptionPane.showInputDialog("Enter The Student's Last Name: ");
               for ( int j=0; j<secondname.length(); j++ )
               if(!Character.isLetter(secondname.charAt(j)))
                    secondnamecheck=false;
                    secondname=JOptionPane.showInputDialog ("Invalid Entry: \n You have entered an integer. \nPlease Re-enter Sudent's last name: ");
          boolean studentidcheck=false;
          do
                    studentid = JOptionPane.showInputDialog("Student Id is the Student's Social Security Number.\nEnter The Student's ID #: ");
          if (studentid.length()!=9)
                    JOptionPane.showMessageDialog(
                         null,
                         "INVALID ENTRY: PLEASE ENTER 9 DIGITS WITHOUT DASHES.",
                         "ERROR", JOptionPane.ERROR_MESSAGE);
          else {
               for ( int j=0; j < studentid.length(); j++ ){
                              if(!Character.isDigit(studentid.charAt(j)))
                                        JOptionPane.showMessageDialog(
                              null,
                              "INVALID ENTRY: YOU HAVE ENTERED LETTERS.",
                              "ERROR", JOptionPane.ERROR_MESSAGE);
                              else {
                                   studentid_int= Integer.parseInt(studentid);
                                   if      (studentid_int<0)
                                        JOptionPane.showMessageDialog(
                              null,
                              "INVALID ENTRY: YOU HAVE ENTERED A NEGATIVE NUMBER.",
                              "ERROR",
                              JOptionPane.ERROR_MESSAGE);
                                   else studentidcheck=true;
               } while (studentidcheck==false);
          midtermgrade = JOptionPane.showInputDialog("This is worth 40% of Student's Grade.\nEnter Mid-term Grade: ");
          midterm_grade = Integer.parseInt( midtermgrade);
          while ( (midterm_grade < 0) || (midterm_grade > 100) )
                    midtermgrade=JOptionPane.showInputDialog ("Invalid Entry!\nA grade entered must be between (0-100).\nPleae Re-Enter Mid-term Grade: ");
                    midterm_grade = Integer.parseInt( midtermgrade);
          finalgrade = JOptionPane.showInputDialog("This is worth 60% of Student's Grade.\nEnter Final Grade:");
          final_grade= Integer.parseInt( finalgrade);
          while ( (final_grade<0) || (final_grade > 100) )
                    finalgrade= JOptionPane.showInputDialog ("Invalid Entry!\nA grade entered must be between (0-100).\nPleae Re-Enter the Final's Grade: ");
                    final_grade= Integer.parseInt( finalgrade);
          DecimalFormat twoDigits = new DecimalFormat( "0.00");
          //calculations for grades
               //midterm is worth 40% of grade
          midterm_gradevalue = midterm_grade * .4;
               //final is worth 60% of grade
          final_gradevalue = final_grade * .6;
               //calculates the final grade for the student in class
          total_gradevalue = midterm_gradevalue + final_gradevalue;
          //if else statement for grade allotment
          if (total_gradevalue>=90)
               lettergrade='A';
          else if (total_gradevalue>=80)
               lettergrade='B';
          else if (total_gradevalue>=70)
               lettergrade='C';     
          else if (total_gradevalue>=60)
               lettergrade='D';     
          else if (total_gradevalue>=50)
               lettergrade='F';          
          //Shows Output of Information Entered (5) of one student               
          JOptionPane.showMessageDialog
               (null, "Student: " + secondname + " , " + firstname +
                    "\nMid-Term Points Earned: " + midterm_gradevalue +
                    "\nFinal Points Earned: " + final_gradevalue +
                    "\nTotal Points Earned: " + total_gradevalue +
                    "\nGrade Assigned: "+ lettergrade,
                    "\n STUDENT ID #: " + studentid,
                    JOptionPane.PLAIN_MESSAGE);
          /*Askes user whether or not to input an additional student*/
          option = JOptionPane.showInputDialog("Enter < 0 > to input a student. \nEnter < -1 > to quit. ");
          //converts string input into integer loop     
          loop = Integer.parseInt( option );
     listings +="Student ID #: " + studentid +
               "\n [ " + secondname + ", " + firstname + " ] " +
               "\n Midterm Points Earned: " + midterm_gradevalue +
               "\n Final Points Earned: " + final_gradevalue +
               "\n Total Points Earned: " + total_gradevalue +
               "\n**********Grade Assigned: "+ lettergrade + "\n";
          } while ( loop !=-1);     
          JOptionPane.showMessageDialog(
               null, listings,
               "Class Results: ",
               JOptionPane.PLAIN_MESSAGE);
          System.exit ( 0 );
     }//end of programming method
}//end of class definition

using arrays is pretty simple. You may want to clean up your code a bit, and place declerations outside of the main method, and create some smaller methods that dow rok, rather then having main carry the whole load. try something like this:
public class GradeWatch9
Student [] studentFile=new Student[50]; /*makes an array with 50 cells
*here I used another class, Student, which you will have to write. the Student class could be as small as two data fields, String name and int grade.
  public static void main ( String args[] )
     for(int i=0;i<studentFile.length;i++)
         String name=getNextName();  //method you write to get the name
         studentFile=new Student(name);
int grade=getGrade(); /*method to get and calculate grades*/
studentFile[i].setGrade(grade);
getNextName()
//gets the students name
getGrade()
//gets and calculates grade
public class Student
int grade
String name
Student(String n)
name=n;
public void setGrade(int g)
grade=g;
see if that helps a bit :)

Similar Messages

  • How to implement array of objects or vector of objects?

    Hello, i am working on a javabean that is connecting to a database and executes an sql string. The javabean returns the records retrieved in a tabular format.
    Currently i can achieve the above requireement, but only through using a simple table-formatted string, this is not dynamic and a 2d array approach would not be dynamic either.
    I have read a little about using a dynamic approach, possiblya vector of objects, or array list of objects to solve the problem, but i don't really know how to start, could anybody help me??
    The code i have so far is:
    package webtech;
    import java.sql.*;
    public class questiona {
    /* Step 1) Initialize Variables*/
    String result = "";
    String query = "select id, name, url, thumb_url, keywords, category, author from mytable;";
    String url = "";
    String driver = "";
    String uname = "";
    String dpass = "";
    /*Step 2) Make a database connection*/
    private Connection dbconn = null;
    public questiona()
    try
    Class.forName(driver);
    dbconn = DriverManager.getConnection(url, uname, dpass);
    /*Create an SQL statement*/
    Statement statement = dbconn.createStatement();
    if (statement.execute(query))
    {/*Step 3) If we have a result lets loop through*/
    ResultSet results = statement.getResultSet();
    ResultSetMetaData metadata = results.getMetaData();
    /*Validate result. Note switch to while loop if we plan on multiple results from query*/
    if(results != null)
    /*Use results setmetadata object to determine the columns*/
    int li_columns = metadata.getColumnCount();
    result += " <tr>\n\r";
    result += " <td>" + metadata.getColumnLabel(1) + "</td>\n\r";
    result += " <td>" + metadata.getColumnLabel(2) + "</td>\n\r";
    result += " <td>" + metadata.getColumnLabel(3) + "</td>\n\r";
    result += " <td>" + metadata.getColumnLabel(4) + "</td>\n\r";
    result += " <td>" + metadata.getColumnLabel(5) + "</td>\n\r";
    result += " <td>" + metadata.getColumnLabel(6) + "</td>\n\r";
    result += " <td>" + metadata.getColumnLabel(7) + "</td>\n\r";
    result += " </tr>\n\r";
    /*loop throught the columns and append data to our table*/
    while(results.next())
    result += " <tr>\n\r";
    result += " <td>" + results.getObject(1).toString() +"</td>\n\r";
    result += " <td>" + results.getObject(2).toString() +"</td>\n\r";
    result += " <td>" + results.getObject(3).toString() +"</td>\n\r";
    result += " <td>" + results.getObject(4).toString() +"</td>\n\r";
    result += " <td>" + results.getObject(5).toString() +"</td>\n\r";
    result += " <td>" + results.getObject(6).toString() +"</td>\n\r";
    result += " <td>" + results.getObject(7).toString() +"</td>\n\r";
    result += " </tr>\n\r";
    catch (ClassNotFoundException e)
    {     result = "<tr><td> Error in database";
    result += " <br/>" + e.toString() + "</td></tr>";
    catch (SQLException e)
    {     result = "<tr><td> Error in SQL";
    result += " <br/>" + e.toString() + "</td></tr>";
    finally
    try {
    if (dbconn !=null)
    { dbconn.close();}
    catch (SQLException e)
    {   result  = " <tr><td> Error in closing connection.";
    result += " <br/>" + e.toString() + "</td></tr>";
    public String getResults() {
    return result;
    }

    Cross-post
    http://forum.java.sun.com/thread.jspa?threadID=604770

  • Implementing Arrays - Problem!

    Hi,
    I am an novice Java programmer and i am having some trouble with arrays, I have written a program that calculates grades, but it does not use arrays. I would like to use arays in my program and at the same time have it support up to 50 people. Please help me in this matter, thanks,
    Martin
    import javax.swing.JOptionPane;
    import java.text.DecimalFormat;
    public class GradeWatch9{//start of class definition GradeWatch
    public static void main ( String args[] ) {//start of main method
    //string declarations
    String firstname;
    String secondname;
    String studentid;
    String midtermgrade;
    String finalgrade;
    String listings="";
    String option;//variable used to receive user's option <-1>//<0>
    //character declarations
    char actualgrade;//letter grade assigned to total points earned
    char lettergrade=0;//assignment of a letter grade
    //integer declarations
    int loop=0;//(this will be converted fr. option//will compare result)
    int studentid_int;
    int midterm_grade=0;
    int final_grade=0;
    double midterm_gradevalue=0;//point calculations
    double final_gradevalue=0;//point calculations
    double total_gradevalue=0;//total points possible out of 100
    do
    //input dialogs (5) with validations
    boolean firstnamecheck=false;
    firstname = JOptionPane.showInputDialog("Enter The Student's First Name: ");
    for ( int j=0; j<firstname.length(); j++ )
    if(!Character.isLetter(firstname.charAt(j)))
    firstnamecheck=false;
    firstname=JOptionPane.showInputDialog("Invalid Entry: \n You have entered an integer. \nPlease Re-enter Sudent's first name: ");
    boolean secondnamecheck=false;
    secondname = JOptionPane.showInputDialog("Enter The Student's Last Name: ");
    for ( int j=0; j<secondname.length(); j++ )
    if(!Character.isLetter(secondname.charAt(j)))
    secondnamecheck=false;
    secondname=JOptionPane.showInputDialog ("Invalid Entry: \n You have entered an integer. \nPlease Re-enter Sudent's last name: ");
    boolean studentidcheck=false;
    do
    studentid = JOptionPane.showInputDialog("Student Id is the Student's Social Security Number.\nEnter The Student's ID #: ");
    if (studentid.length()!=9)
    JOptionPane.showMessageDialog(
    null,
    "INVALID ENTRY: PLEASE ENTER 9 DIGITS WITHOUT DASHES.",
    "ERROR", JOptionPane.ERROR_MESSAGE);
    else {
    for ( int j=0; j < studentid.length(); j++ ){
    if(!Character.isDigit(studentid.charAt(j)))
    JOptionPane.showMessageDialog(
    null,
    "INVALID ENTRY: YOU HAVE ENTERED LETTERS.",
    "ERROR", JOptionPane.ERROR_MESSAGE);
    else {
    studentid_int= Integer.parseInt(studentid);
    if (studentid_int<0)
    JOptionPane.showMessageDialog(
    null,
    "INVALID ENTRY: YOU HAVE ENTERED A NEGATIVE NUMBER.",
    "ERROR",
    JOptionPane.ERROR_MESSAGE);
    else studentidcheck=true;
    } while (studentidcheck==false);
    midtermgrade = JOptionPane.showInputDialog("This is worth 40% of Student's Grade.\nEnter Mid-term Grade: ");
    midterm_grade = Integer.parseInt( midtermgrade);
    while ( (midterm_grade < 0) || (midterm_grade > 100) )
    midtermgrade=JOptionPane.showInputDialog ("Invalid Entry!\nA grade entered must be between (0-100).\nPleae Re-Enter Mid-term Grade: ");
    midterm_grade = Integer.parseInt( midtermgrade);
    finalgrade = JOptionPane.showInputDialog("This is worth 60% of Student's Grade.\nEnter Final Grade:");
    final_grade= Integer.parseInt( finalgrade);
    while ( (final_grade<0) || (final_grade > 100) )
    finalgrade= JOptionPane.showInputDialog ("Invalid Entry!\nA grade entered must be between (0-100).\nPleae Re-Enter the Final's Grade: ");
    final_grade= Integer.parseInt( finalgrade);
    DecimalFormat twoDigits = new DecimalFormat( "0.00");
    //calculations for grades
    //midterm is worth 40% of grade
    midterm_gradevalue = midterm_grade * .4;
    //final is worth 60% of grade
    final_gradevalue = final_grade * .6;
    //calculates the final grade for the student in class
    total_gradevalue = midterm_gradevalue + final_gradevalue;
    //if else statement for grade allotment
    if (total_gradevalue>=90)
    lettergrade='A';
    else if (total_gradevalue>=80)
    lettergrade='B';
    else if (total_gradevalue>=70)
    lettergrade='C';
    else if (total_gradevalue>=60)
    lettergrade='D';
    else if (total_gradevalue>=50)
    lettergrade='F';
    //Shows Output of Information Entered (5) of one student
    JOptionPane.showMessageDialog
    (null, "Student: " + secondname + " , " + firstname +
    "\nMid-Term Points Earned: " + midterm_gradevalue +
    "\nFinal Points Earned: " + final_gradevalue +
    "\nTotal Points Earned: " + total_gradevalue +
    "\nGrade Assigned: "+ lettergrade,
    "\n STUDENT ID #: " + studentid,
    JOptionPane.PLAIN_MESSAGE);
    /*Askes user whether or not to input an additional student*/
    option = JOptionPane.showInputDialog("Enter < 0 > to input a student. \nEnter < -1 > to quit. ");
    //converts string input into integer loop
    loop = Integer.parseInt( option );
    listings +="Student ID #: " + studentid +
    "\n [ " + secondname + ", " + firstname + " ] " +
    "\n Midterm Points Earned: " + midterm_gradevalue +
    "\n Final Points Earned: " + final_gradevalue +
    "\n Total Points Earned: " + total_gradevalue +
    "\n**********Grade Assigned: "+ lettergrade + "\n";
    } while ( loop !=-1);
    JOptionPane.showMessageDialog(
    null, listings,
    "Class Results: ",
    JOptionPane.PLAIN_MESSAGE);
    System.exit ( 0 );
    }//end of programming method
    }//end of class definition

    You should use a List instead, it will be more maintainable if you want this program to work for more students, without having to edit the souce:
    List students = new ArrayList(); // Create a List
    // To add students
    students.add(student);
    // To iterate through them
    Iterator it = students.iterator();
    while(it.hasNext)
    Student s = (Student)it.next();
    // For direct access
    Student s = (Student)students.get(index);
    class Student extends Object
    private String firstName;
    private String secondName;
    private String id;
    private String midtermGrade;
    private String finalGrade;
    public Student()
    // Add a setter/getter for each variable
    also override toString()
    now with this bean, you could open an option pane passing a JList that was create with the passed in List

  • Having problem implementing array in code?

    I am trying to write a code that will ask the user to either enter in a name of a reds baseball player, a batting average, or a slugging percentage. When this is entered the name of that corresponding player will pop up along with his stats. The code that I have so far is written below. I just need help in the three areas of my if statements so that if the user types in a name, average, or slug percentage then that player and stats will come up from the file in my program(stats.txt).
    import javax.swing.*;
    import java.io.*;
    public class BattingStats
    public static void main(String[]args) throws IOException
    String option=selectOption("Select a search option"))
    getPlyrName();
    //need help here?
    if(option.equals("listBatAvg"))
    //need help here?
    if(option.equals("listSlug"))
    //need help here?
    private static void readSomeLines() throws IOException
    String filename="stats.txt";
    FileReader fr=new FileReader( filename);
    BufferedReader br=new Buffered Reader (fr);
    String sLine=br.readLine();
    while (sLine != null)
    String[] stats = sLine.split("\t");
    sLine=br.readLine();
    br.close();
    public static String selectOption (String prompt)
    String option=" ";
    int choice= JOptionPane.showOptionDialog(null, prompt, "Cinncinnati Reds player stats", JOptionPane.DEFAULT_OPTION, new Object[]
    "Search for a particular players stats", "List stats in decending order based on slugging percentage"
    if (choice==0)
    option="searchPlyr";
    if(choice==1)
    option="listBatAvg";
    if(choice==2)
    option="listSlug";
    return option;
    public static String getPlyrName () throws IOException
    String name=JOptionPane.showInputDialog(null, "Enter players name?");
    return name;
    }

    I assume that there will be more than one line in each txt file. Your code appears to loop through the file lines but does nothing with them. I think you need something like:
    import java.util.ArrayList;
    ArrayList allResults = new ArrayList();   //Declared at the top of your program
    allResults.add(stats);
    I reproduce your code below with some amendments.  I think you would have a hard time compiling this without my amendments.  I am not sure about some of the details but atleast it will now compile.  You should compile and run your code regularly so that you only have one or two errors to deal with.  You should add occasional System.out.println("Message") statements to help you understand what the code is doing.  You can comment them out when you are confident.
    import javax.swing.*;
    import java.io.*;
    public class BattingStats
         public static void main(String[]args) throws IOException
              // OK Java is object oriented so get rid of static and
              // create a BattingStats object
              BattingStats b = new BattingStats();
         public BattingStats()
              String player = "";
              String option=selectOption("Select a search option"); //Removed surplus bracket
              try
                   player = getPlyrName();
              catch (IOException ioe)
                   System.out.println("Error in getting Player name");
                   System.out.println("Program terminating");
                   System.exit(1);
                   //need help here?     <<< Sort out file reading first
              if(option.equals("listBatAvg"))
                   //need help here?
              if(option.equals("listSlug"))
                   //need help here?
         private void readSomeLines() throws IOException    // Static removed
              String filename="stats.txt";
              FileReader fr=new FileReader( filename);
               //BufferedReader br=new Buffered Reader (fr);
              BufferedReader br=new BufferedReader (fr);
              String sLine=br.readLine();
              while (sLine != null)
                   String[] stats = sLine.split("\t");
                   sLine=br.readLine();
                   //The above is fine but surely you have more than one line
                   //if so your data is being read and dropped.
                   // I guess you need to create an ArrayList and add each
                   // stats line to it
              br.close();
         public String selectOption (String prompt)   //Static removed
              String option=" ";
              //int choice= JOptionPane.showOptionDialog(null, prompt, "Cinncinnati Reds player stats", JOptionPane.DEFAULT_OPTION, new Object[]
              //"Search for a particular players stats", "List stats in decending order based on slugging percentage"
              String[] optionArray = {
                        "Player stats",
                        "Batting average",
                        "Slugging percentage"
              int choice= JOptionPane.showOptionDialog(
                        null,
                        prompt,
                        "Cinncinnati Reds player stats",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        optionArray,
                        optionArray[1]
              if (choice==0)
                   option="searchPlyr";  //Where is this used
              if(choice==1)
                   option="listBatAvg";
              if(choice==2)
                   option="listSlug";
              return option;
         public String getPlyrName () throws IOException   //Static removed
              String name=JOptionPane.showInputDialog(null, "Enter players name?");
              return name;
    }Please note that by highlighting the code and pressing the code button it keeps the formatting. This is why you can see the indents above.

  • Multidimensional array as argument to a Java method

    Hello all,
    I have defined in C the following array :
    char my_array[100][3];I want to pass this mutidimensional array to a Java method. How should I write my C array as an argument of the Java method ?
    TIA

    You cannot do that in a straight-forward fassion. The C compiler reserves 300 consecutive bytes in memory, the base address of which is accessible through my_array. The base address of each of your 100 rows can be accessed as my_array[row]. The length of each row is fixed and only known to the programmer and the compiler which uses it to calculate the row offsets.
    Java has a slightly different approach to multi-dimensional arrays. Actually they are simply not implemented. What you see and use as multi-dimensional array is a composition of one array holding the references to other arrays - remember, arrays are also only Objects. This implies that the data of different rows does not at all represent a contingious memory region.
    So what you need to do is to allocate an array of size 100, which holds char[]s - references to char-arrays. Then you iterate through your C array and for each row you allocate an char-array of length 3 initialized to the appropriate row. The references to those char-arrays need to be stored in the char[]-array.
    Use env->NewCharArray(env, length) to create a new char[] and env->NewObjectArray(env, length, clazz, null) to create the char[][]. Accesing the elements of these arrays is described in:
    http://java.sun.com/docs/books/tutorial/native1.1/implementing/array.html

  • I have no idea where to start

    okay, hi! i'm trying to write a vending machine program for a class i'm taking. i have a text file with names, image URLs, and prices. I have a product class which is supposed to use filereader to read the fields in the text file. The product class is going to be loaded by the main VendMach class file, where i will have all of the main ui stuff written. The last file is the MoneyInOut class, which handles all of the money methods. i've got the majority of the UI file done, the text file is ready, and the money file is almost done...everything is hanging on whether or not i can write the product file. i have no idea where to start. any help would be greatly appreciated. i'm not looking for somebody else to write my code, but a point in the right direction would be great! here are the UI and text files:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import java.util.StringTokenizer;
    // Still to be fixed:
    // 1. Purchase & Maintenance buttons.
    // 2. fix repaint of pictures, they don't display until a repaint is hit.
    // 3. fix the Quit from program, it doesn't work right.
    // 4. Put in the code for doing Maintenance.
    // 5. Button super.setSize
    // 6. Animate picture on selection.
    public class VendMach extends Applet implements ActionListener
    // Fonts for text and buttons.
    private Font boldSerif16 = new Font("Serif",Font.BOLD,16);
    private Font boldSerif24 = new Font("Serif",Font.BOLD,24);
    private Font boldItalicSerif24 = new Font("Serif",Font.BOLD+Font.ITALIC,24);
    private Font boldItalicSerif13 = new Font("Serif",Font.BOLD+Font.ITALIC,13);
    private Font boldItalicSerif40 = new Font("Serif",Font.BOLD+Font.ITALIC,40);
    //%% private Font boldItalicDialog16 = new Font("Dialog",Font.BOLD+Font.ITALIC,16);
    // Mode flag.
    private int mode = 0;
    // Panels for the buttons
    private Panel mainPanel = new Panel();
    private Panel cashPanel = new Panel();
    private Panel selPanel = new Panel();
    private Panel maintPanel = new Panel();
    // Product selection panel buttons
    private Button selBtn[] = new Button[6];
    // Cash customer puts in machine panel buttons
    private Button viewC = new Button("View The Products");
    private Button quit = new Button("Quit");
    private Button bNickle = new Button("Nickel");
    private Button bDime = new Button("Dime");
    private Button bQuarter = new Button("Quarter");
    private Button b$Paper = new Button("$1 Paper");
    private Button b$Coin = new Button("$1 Coin");
    private Label lCredit = new Label(" Credit:");
    private Label lMsg = new Label("");
    private Button bChange = new Button("Change Return");
    private Button purchase = new Button("Purchase");
    private Button maintenance = new Button("Maintenance");
    private Product productForSale [];
    private CashIn changeOH;
    private int $collected = 0;
    private double total$In = 0.00;
    private NumberFormat nf;
    private Image pic;
    private Image picAnim;
    private int prodSel = 999;
    private String line;
    private String f[] = new String[8];
    private int tokenCount;
    private int int3, int4, int5, int6, int7;
    private double dbl4;
    private StringTokenizer strings;
    private int dispense = 99;
    public void init()
    {  setLayout(new BorderLayout());
    productForSale = new Product[6];
    try
    {  BufferedReader inPut = new BufferedReader(new FileReader("Vend_Machine.txt"));
    while ((line=inPut.readLine()) != null)
    {  strings = new StringTokenizer(line,",");
    tokenCount = strings.countTokens();
    // Loop thru and retrieve each data element.
    for (int i=0; i<tokenCount; i++)
    f[i] = strings.nextToken();
    // Load the money.
    if (f[0].compareTo("M") == 0)
    {  int3 = Integer.parseInt(f[3]);
    int4 = Integer.parseInt(f[4]);
    int5 = Integer.parseInt(f[5]);
    int6 = Integer.parseInt(f[6]);
    int7 = Integer.parseInt(f[7]);
    changeOH = new CashIn(f[1],f[2],int3,int4,int5,int6,int7);
    // Load the products.
    if (f[0].compareTo("P") == 0)
    {  int3 = Integer.parseInt(f[3]);
    dbl4 = (new Double(f[4])).doubleValue();
    int5 = Integer.parseInt(f[5]);
    int6 = Integer.parseInt(f[6]);
    int7 = Integer.parseInt(f[7]);
    productForSale[int3] = new Product(f[1],f[2],dbl4,int5,int6,int7);
    inPut.close();
    catch(IOException e)
    {  e.printStackTrace();
    setBackground(Color.pink);
    setForeground(new Color(120,0,120));
    setFont(boldSerif16);
    cashPanel.setLayout(new GridLayout(10,1));
    cashPanel.add(viewC);
    cashPanel.add(quit);
    cashPanel.add(bNickle);
    cashPanel.add(bDime);
    cashPanel.add(bQuarter);
    cashPanel.add(b$Paper);
    cashPanel.add(b$Coin);
    cashPanel.add(lCredit);
    cashPanel.add(lMsg);
    cashPanel.add(bChange);
    add(cashPanel,"East");
    selPanel.setLayout(new GridLayout(1,6));
    for (int i=0; i<6; i++)
    {  selBtn[i] = new Button(productForSale.getName());
    selPanel.add(selBtn[i]);
    add(selPanel,"South");
    setBackground(Color.black);
    viewC.addActionListener(this);
    quit.addActionListener(this);
    bNickle.addActionListener(this);
    bDime.addActionListener(this);
    bQuarter.addActionListener(this);
    b$Paper.addActionListener(this);
    b$Coin.addActionListener(this);
    bChange.addActionListener(this);
    nf = NumberFormat.getCurrencyInstance();
    for (int i=0; i<6; i++)
    selBtn[i].addActionListener(this);
    } // =======>> END OF INIT METHOD
    // ** PAINT METHOD **
    public void paint(Graphics g)
    {  int xVal = 35;
    int yVal = 85;
    int xValAnim = 0;
    int yValAnim = 0;
    int c = 0;
    // Paint the product pictures on the vending machine.
    g.setColor(Color.cyan);
    g.setFont(boldItalicSerif24);
    g.drawString(changeOH.getLogo1(),115,40);
    g.setFont(boldItalicSerif13);
    g.drawString(changeOH.getLogo2(),200,60);
    for (int z=0; z<2; z++)
    {  xVal = 35;
    yVal = 85;
    c = 0;
    g.setColor(Color.black);
    g.fillRect(xVal,yVal,500,350);
    g.setColor(Color.yellow);
    for (int i=0; i<2; i++)
    {  for (int j=0; j<3; j++)
    {  g.setFont(boldSerif16);
    g.drawString(nf.format(productForSale[c].getPrice()),xVal+45,yVal-5);
    pic = getImage(getCodeBase(),productForSale[c].getPic());
    g.drawImage(pic,xVal,yVal,null);
    // If product is dispensed get ready to animate.
    if (c == dispense)
    {  xValAnim = xVal;
    yValAnim = yVal;
    picAnim = pic;
    xVal = xVal + 170;
    c++;
    yVal = yVal + 160;
    xVal = 35;
    // If product is dispensed, animate it.
    if (dispense < 99)
    {  for (int y=0; y<40; y++)
    {  g.setColor(Color.black);
    g.fillRect(xValAnim,yValAnim-9,125,125);
    g.setColor(Color.yellow);
    g.drawImage(picAnim,xValAnim,yValAnim,null);
    yValAnim = yValAnim + 10;
    pause(3);
    dispense = 99;
    if (mode == 0)
    {  pic = getImage(getCodeBase(),"OutStock.gif");
    g.drawImage(pic,300,300,null);
    g.setColor(Color.black);
    g.fillRect(1,1,500,300);
    g.setColor(Color.pink);
    g.setFont(boldItalicSerif40);
    g.drawString(changeOH.getLogo1(),10,150);
    g.setFont(boldItalicSerif24);
    g.drawString(changeOH.getLogo2(),160,250);
    mode++;
    } // =======>> END OF PAINT METHOD
    // ** ACTIONPERFORMED METHOD **
    public void actionPerformed(ActionEvent event)
    {  Object source = event.getSource();
    lMsg.setText(" Enter up to $1.00");
    // Customer puts money in the vending machine.
    // Customer paid a nickle
    if (source == bNickle && $collected < 96)
    {  changeOH.nickleIn();
    $collected = $collected + 5;
    // Customer paid a dime
    if (source == bDime && $collected < 91)
    {  changeOH.dimeIn();
    $collected = $collected + 10;
    // Customer paid a quarter
    if (source == bQuarter && $collected < 76)
    {  changeOH.quarterIn();
    $collected = $collected + 25;
    // Customer paid a paper dollar
    if (source == b$Paper && $collected == 0)
    {  changeOH.dollarPaperIn();
    $collected = $collected + 100;
    // Customer paid a coin dollar
    if (source == b$Coin && $collected == 0)
    {  changeOH.dollarCoinIn();
    $collected = $collected + 100;
    // Customer makes their product selection.
    for (int i=0; i<6; i++)
    {  if (source == selBtn[i])
    // Do nothing if customer selects item that isn't on-hand.
    if (productForSale[i].getOnHand() == 0)
    repaint();
    // We have product on-hand.
    else
    {  prodSel = i;
    // Tell customer to add more money if they don't have
    // enough in the machine to handle the purchase.
    if ($collected < (int) (productForSale[i].getPrice() * 100))
    { lMsg.setText("    Insert Money");
    // Customer has enough money in machine to cover purchase.
    else
    {  // Take cost of item from customer's money
    dbl4 = productForSale[i].getPrice() * 100;
    int4 = changeOH.giveChange($collected - (int)dbl4,0);
    // Tell customer to put exact amount in the machine
    // because there isn't enough change to handle purchase.
    if (int4 == 9)
    {  lMsg.setText("Exact Amount Only!");
    // **** Here the purchase was made and committed. ****
    else
    {  total$In = productForSale[i].getPrice() * 100;
    $collected = $collected - (int) total$In;
    productForSale[i].sellProduct();
    dispense = i;
    repaint();
    // If the last product item was sold, set picture to OutStock.gif.
    if (productForSale[i].getOnHand() <= 0)
    productForSale[i].setOutOfStock();
    if ((source == bChange || source == quit) && $collected > 0)
    {  $collected = changeOH.giveChange($collected,1);
    // Here we save the machine info file when customer asks
    // for their change back or quits the machine.
    // Customer has selected to Quit the vending machine program.
    // Quit the program.
    if (source == quit)
    System.exit(0);
    // These commands set up variables to show how much money
    // the customer has in the machine.
    total$In = $collected;
    total$In = total$In / 100;
    lCredit.setText(" Credit: " + nf.format(total$In));
    repaint();
    } // =======>> END OF ACTIONPERFORMED METHOD
    // ** PAUSE METHOD **
    public void pause(int i)
    {  for(long l = System.currentTimeMillis() + (long) i; System.currentTimeMillis() < l;);
    // =======>> END OF VENDMACH CLASS APPLET
    // ** CASHIN CLASS **
    class CashIn
    {  private String logo1;
    private String logo2;
    private int numProd;
    private int nickles;
    private int dimes;
    private int quarters;
    private int dollarsP;
    private int dollarsC;
    private int money;
    private double moneyVal;
    private int amtToChange = 0;
    private int hNickle;
    private int hDime;
    private int hQuarter;
    private int hpDollar;
    private int hcDollar;
    public CashIn(String l1, String l2, int p, int q, int d, int n, int dP)
    {  logo1    = l1;
    logo2 = l2;
    numProd = p;
    quarters = q;
    dimes = d;
    nickles = n;
    dollarsP = dP;
    dollarsC = 0;
    money = (n * 5) + (d * 10) + (q * 25) + (dP * 100);
    // Get total of money in machine.
    public double getCashIn()
    {  moneyVal = money;
    moneyVal = moneyVal / 100;
    return moneyVal;
    // Get machine record information.
    public String getLogo1()
    {  return logo1;
    public String getLogo2()
    {  return logo2;
    public int getNumProd()
    {  return numProd;
    public int getNickles()
    {  return nickles;
    public int getDimes()
    {  return dimes;
    public int getQuarters()
    {  return quarters;
    public int getDollarPaper()
    {  return dollarsP;
    public int getDollarCoins()
    {  return dollarsC;
    // Money comes into the machine
    public void nickleIn()
    {  nickles++;
    money = money + 05;
    public void dimeIn()
    {  dimes++;
    money = money + 10;
    public void quarterIn()
    {  quarters++;
    money = money + 25;
    public void dollarPaperIn()
    {  dollarsP++;
    money = money + 100;
    public void dollarCoinIn()
    {  dollarsC++;
    money = money + 100;
    // Give the customer their change.
    public int giveChange(int custMoney, int mode)
    {  hNickle   = nickles;
    hDime = dimes;
    hQuarter = quarters;
    hpDollar = dollarsP;
    hcDollar = dollarsC;
    amtToChange = custMoney / 100;
    for (int i=0; i<amtToChange; i++)
    {  // Give change in dollar coin if possible
    if (hcDollar > 0)
    {  hcDollar--;
    custMoney = custMoney - 100;
    // or else give change in paper dollar
    else
    {  if (hpDollar > 0)
    {  hpDollar--;
    custMoney = custMoney - 100;
    amtToChange = custMoney / 25;
    for (int i=0; i<amtToChange; i++)
    {  if (hQuarter > 0)
    {  hQuarter--;
    custMoney = custMoney - 25;
    amtToChange = custMoney / 10;
    for (int i=0; i<amtToChange; i++)
    {  if (hDime > 0)
    {  hDime--;
    custMoney = custMoney - 10;
    amtToChange = custMoney / 5;
    if (amtToChange > hNickle)
    {  mode = 9;
    for (int i=0; i<amtToChange; i++)
    {  hNickle--;
    custMoney = custMoney - 5;
    if (mode == 1)
    {  nickles   = hNickle;
    dimes = hDime;
    quarters = hQuarter;
    dollarsP = hpDollar;
    dollarsC = hcDollar;
    money = money - custMoney;
    if (mode == 9) custMoney = 9;
    return custMoney;
    } // =======>> END OF CASHIN CLASS
    // ** PRODUCT CLASS **
    class Product
    {  private String name;
    private String image;
    private String picUsed;
    private double price;
    private int onHand;
    private int sold;
    private int maint;
    public Product(String n, String i, double p, int o, int s, int m)
    {  name    = n;
    image = i;
    picUsed = i;
    price = p;
    onHand = o;
    sold = s;
    maint = m;
    // Reset picture used when product is out of stock.
    public void setOutOfStock()
    {  picUsed  = "OutStock.gif";
    // Get product information
    public String getName()
    {  return name;
    public String getImage()
    {  return image;
    public String getPic()
    {  return picUsed;
    public double getPrice()
    {  return price;
    public int getOnHand()
    {  return onHand;
    public int getQtySold()
    {  return sold;
    public int getMaintDate()
    {  return maint;
    // Sell one of the product.
    public void sellProduct()
    {  onHand--;
    sold++;
    // Set the product values.
    public void setName(String n)
    {  name = n;
    public void setImage(String i)
    {  image   = i;
    picUsed = i;
    public void setPrice(double p)
    {  price = p;
    public void setOnHand(int o)
    {  onHand = o;
    public void setQtySold(int s)
    {  sold = s;
    public void setMaintDate(int m)
    {  maint = m; }
    this is the text file
    p,Fritos,Images/FritoLay.gif,
    m,$.50,
    p,Dr. Pepper,Images/Dr.Pepper.gif,
    m,$.60,
    p,Pepsi,Images/Pepsi.gif,
    m,$.60,
    p,Coke,Images/CocaCola.gif,
    m,$.60,
    p,Seven-Up,Images/7-Up.gif,
    m,$.60,
    p,Sprite,Images/Sprite.gif,
    m,$.60,
    c,10,20,40,
    i know that the filereader is supposed to read the fields...i guess i just have a weak start on understanding and implementing arrays.

    I write this sample some time ago, you can use it to start a new project
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CVM extends JFrame 
         JTextField mw = new JTextField("0");     
         JTextField hf = new JTextField("0");     
         JTextField ds = new JTextField("0");     
         JTextField lr = new JTextField("0");     
         JTextField py = new JTextField("0");     
         JTextField tp = new JTextField("0");     
         JTextField ch = new JTextField("0");     
    public CVM()
         super("Chocolate Vending Machine");
         setBounds(0,0,500,400);
         addWindowListener(new WindowAdapter()
         {      public void windowClosing(WindowEvent ev)
                   dispose();
                   System.exit(0);
         JPanel pan = new JPanel();
    //     pan.setLayout(new GridLayout(0,2,4,4));
         JPanel lp = new JPanel();
         lp.setBackground(Color.pink);
         lp.setLayout(new GridLayout(16,2,4,4));
         addButton(lp,"Milky Way    20$",mw);
         addButton(lp,"Hot Fudge    40$",hf);
         addButton(lp,"Dandy Shandy 50$",ds);
         addButton(lp,"Lovers Rock  80$",lr);
         addClearButton(lp);
         lp.add(new JLabel(""));
         lp.add(new JLabel(""));
         addPayButtons(lp);
         addMoneyBack(lp);
         pan.add(lp);
         setContentPane(pan);
         setVisible(true);
    private void addPayButtons(JPanel pan)
         JPanel lp = new JPanel();
         lp.setOpaque(false);
         lp.setLayout(new GridLayout(0,2,4,4));
         JButton b1 = new JButton("Pay 5");
         addPay(b1,5);
         b1.setMargin(new Insets(0,0,0,0));
         JButton b2 = new JButton("Pay 10");
         addPay(b2,10);
         b2.setMargin(new Insets(0,0,0,0));
         lp.add(b1);
         lp.add(b2);
         pan.add(lp);
         lp = new JPanel();
         lp.setOpaque(false);
         lp.setBackground(Color.cyan);
         lp.setLayout(new GridLayout(0,2,4,4));
         JButton b3 = new JButton("Pay 20");
         addPay(b3,20);
         b3.setMargin(new Insets(0,0,0,0));
         JButton b4 = new JButton("Pay 50");
         addPay(b4,50);
         b4.setMargin(new Insets(0,0,0,0));
         lp.add(b3);
         lp.add(b4);
         pan.add(lp);
         pan.add(new JLabel("    Payd"));
         pan.add(py);
    private void addPay(JButton bt, final int i)
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   int n = Integer.parseInt(py.getText())+i;
                   py.setText(""+n);
                   calculate();
    private void addButton(JPanel pan, String s, final JTextField jt)
         JButton    bt = new JButton(s);
         bt.setHorizontalAlignment(SwingConstants.LEFT);
         bt.setMargin(new Insets(0,0,0,0));
         pan.add(bt);
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   int i = Integer.parseInt(jt.getText())+1;
                   jt.setText(""+i);
                   calculate();
         jt.setHorizontalAlignment(SwingConstants.CENTER );
         jt.setEditable(false);
         jt.setBackground(Color.white);
         pan.add(jt);
    private void calculate()
         int nwi = Integer.parseInt(mw.getText()) * 20;       
         int hfi = Integer.parseInt(hf.getText()) * 40;  
         int dsi = Integer.parseInt(ds.getText()) * 50;  
         int lri = Integer.parseInt(lr.getText()) * 80;  
         int t   = nwi+hfi+dsi+lri;
         if (t >= 100) t = t - (t/10);
         tp.setText(""+t);
         int n = Integer.parseInt(py.getText());
         int c = n-t;
         ch.setText(""+c);
    private void addClearButton(JPanel pan)
         pan.add(new JLabel("    To pay"));
         pan.add(tp);     
         JButton    bt = new JButton("Clear");
         bt.setHorizontalAlignment(SwingConstants.CENTER);
         bt.setMargin(new Insets(0,0,0,0));
         pan.add(bt);
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   mw.setText("0");       
                   hf.setText("0");  
                   ds.setText("0");  
                   lr.setText("0");  
                   tp.setText("0");  
         pan.add(new JLabel(""));
    private void addMoneyBack(JPanel pan)
         JButton    bt = new JButton("Money back");
         bt.setHorizontalAlignment(SwingConstants.CENTER);
         bt.setMargin(new Insets(0,0,0,0));
         pan.add(bt);
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   py.setText("0");
                   ch.setText("0");
         pan.add(new JLabel(""));
         pan.add(new JLabel("    Change"));
         pan.add(ch);     
    public static void main( String[] args)
         new CVM();
    }Noah

  • CORBA  BAD_PARAM/201

    Hi
    I'm having difficulty passing info from my server to my client; primitive data types are no problem, but am not successful in implementing arrays.
    A video file is read into an array in the Server, and upon request from the Client, the Server attempts to pass the array to the Client
    IDL
      typedef string VideoList [100];
      // i have also tried typedef sequence<string> videoList //
       VideoList getVideoList(); Server
        String [] video_list = new String[100];
        public String [] getVideoList()
          return video_list;
    Client
      String [] client_video_list = new String [100];
      client_video_list = helloRef.getVideoList();
    When the Client is executed, it fails on a CORBA.BAD_PARAM /201
    ERROR : org.omg.CORBA.BAD_PARAM: vmcid: SUN minor code: 201 completed: Mayb
    org.omg.CORBA.BAD_PARAM: vmcid: SUN minor code: 201 completed: Maybe
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Metho
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstru
    orAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Delegatin
    onstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
    at java.lang.Class.newInstance0(Class.java:308)
    at java.lang.Class.newInstance(Class.java:261)
    at com.sun.corba.se.internal.iiop.messages.ReplyMessage_1_2.getSystemE
    eption(ReplyMessage_1_2.java:90)
    at com.sun.corba.se.internal.iiop.ClientResponseImpl.getSystemExceptio
    ClientResponseImpl.java:105)
    at com.sun.corba.se.internal.corba.ClientDelegate.invoke(ClientDelegat
    java:314)
    at org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:457)
    at HelloApp1._HelloStub.getVideoList(_HelloStub.java:60)
    at HelloClient.main(HelloClient.java:42)
    Looking up the error code:
    BAD_PARAM/201. vmcid: SUN minor code: 201 literally means "NULL_PARAM". This exception often occurs because a Java null was given to a write method such as write_string, write_octet_array, etc. You cannot return a Java null as the result of a Java method.
    Any ideas ?

    On the server side the video_list is not null .
    Here are some snippets
    Server
      // sayHello -  I call the getVideoList method from this method just to prove that the getVideoList returns an array
       public String sayHello()
          String aString = "from server";
          System.out.println("Well, hello to you too!");
          String [] array = getVideoList();
          System.out.println(array[0]);
          System.out.println("address of array is " + array);
          return aString;
       // getVideoList  - Prints out the 1st element and the address of the array
        public String [] getVideoList()
           System.out.println("1st element in Video List is " + video_list[0]);
           System.out.println("address of video_list is " + video_list);
           return video_list;
      // aVideo  -Returns a specific video from the array ; again to show that the array is not null
         public String aVideo(int x)
           System.out.println("A Video ?");
           System.out.println(video_list[x]);
           return video_list[x];
    client
             System.out.println("Got this ..." + helloRef.sayHello());   
             String a_video = helloRef.aVideo(2);
             System.out.println("3rd video in client video list is ..." + a_video);
              String [] client_video_list = helloRef.getVideoList();            //  fails here
              String video = client_video_list[0];
              System.out.println("1st video in client video list is ..." + video);
    server output
    //  generated from helloRef.sayHello()
    Well, hello to you too!
    1st element in Video List is Harry Potter,1           
    address of video_list is [Ljava.lang.String;@872380
    Harry Potter,1
    address of array is [Ljava.lang.String;@872380
    //  generated from helloRef.aVideo(2)
    A Video ?
    Start Trek,1
    //  generated from helloRef.getVideoList()
    1st element in Video List is Harry Potter,1
    address of video_list is [Ljava.lang.String;@872380
    client output
    //  generated from helloRef.sayHello()
    Got this ...from server
    //  generated from helloRef.aVideo(2)
    3rd video in client video list is ...Start Trek,1
    //  generated from helloRef.getVideoList()
    ERROR : org.omg.CORBA.BAD_PARAM:   vmcid: SUN  minor code: 201 completed: Maybe
    org.omg.CORBA.BAD_PARAM:   vmcid: SUN  minor code: 201 completed: Maybe
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
    orAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
    onstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
            at java.lang.Class.newInstance0(Class.java:308)
            at java.lang.Class.newInstance(Class.java:261)
            at com.sun.corba.se.internal.iiop.messages.ReplyMessage_1_2.getSystemExc
    eption(ReplyMessage_1_2.java:90)
            at com.sun.corba.se.internal.iiop.ClientResponseImpl.getSystemException(
    ClientResponseImpl.java:105)
            at com.sun.corba.se.internal.corba.ClientDelegate.invoke(ClientDelegate.
    java:314)
            at org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:457)
            at HelloApp1._HelloStub.getVideoList(_HelloStub.java:82)
            at HelloClient.main(HelloClient.java:45)So you can see from all this that the video_list is not null ;
    Once again the IDL is as follows:
      module HelloApp1
         typedef sequence<string> videoList;
        // Interface to a hello object
        interface Hello
          string sayHello();
          void sayGoodNight();
          string aVideo(in long x );
          videoList getVideoList();
    };Any ideas ?

  • JbyteArray - char * and jlong - long

    Hi,
    I've been trying to figure out how to convert the following:
    jbyteArray to a char *, void *, or something similar
    jlong to a long
    This is for C++ code.
    I can't seem to figure it out, or find any documentation about this conversion online!!
    Thanks.

    Generally, avoid casting from jlong to long as the definition of long is platform dependent and not necessarily a 64 bit wide. Otherwise a regular cast works here although you may lose bits when casting to a 32-bit integer.
    A byte array can be accessed through the following:
    jsize  len  = (*env)->GetArrayLength(env, arr);
    jbyte *body = (*env)->GetByteArrayElements(env, arr, 0);Casting jbyte to char should not be critical as both are most likely single-byte entities.
    http://java.sun.com/docs/books/tutorial/native1.1/implementing/array.html
    http://java.sun.com/docs/books/tutorial/native1.1/implementing/cpp.html

  • What are appropriate directives for array implementation in hls

    dear friends,
      I have tried hardware implementation in VivadoHLS by passing arrays to the function in Microblaze based soc. The problem I am facing is that the RTL is not being implemented properly.Though the implementation was success for register inputs and outputs , there were no functions generated in the header files in include directory of pcores through which inputs are to be given to hardware while the input and output arguments are arrays in SDK. i need a help to know the appropriate directives for this implementation . And the functions to be used to give inputs after generating hardware and how the final outputs from the hardware are taken. Please clarify the implementation of this basic example.
    void array_add(int z[4],int x[4])
    #pragma HLS INTERFACE ap_fifo port=z
    #pragma HLS INTERFACE ap_fifo port=x
    #pragma HLS RESOURCE variable=z core=AXIS
    #pragma HLS RESOURCE variable=x core=AXIS
    #pragma HLS RESOURCE variable=return core=AXI4LiteS
    int i;
    label0:for(i=0;i<4;i++)
    z[i]=x[i];
    return;
    thanks and regards
    sasidhar

    Hi
    There are couple of directives for this. This can determine the way you want to implement your array or partition this.
    I found a good guide.
    http://users.ece.utexas.edu/~gerstl/ee382v_f14/soc/vivado_hls/VivadoHLS_Improving_Performance.pdf
    Hope this helps.
    Regards
    Sikta

  • Is LabVIEW best for implementating an array of microphones?

    Hello techies,
    I am planning to implement an array of microphones for localization of sound. Is LabVIEW the best for this or does anybody know a better one??
    I would appreciate it if anybody could help me with this.
    thanks in advance ! 

    Stream of consciousness alert.
    My sense is that LabVIEW is not the BEST.
    The best is probably an all-hardware solution.  Very difficult to build, harder to debug, harder still to modify.
    Introduce software, the next best is probably coded in machine language.  Probably harder than all-hardware.
    Next best is to use a low-level language such as C with custom routines optimized for your particular problem.  Hard, but doable and not user-friendly.
    Move to a higher level language such as C++, better UI, slightly worse performance.
    Move to LabVIEW/Measurement Studio.  Slightly worse overhead, great UI, relatively easy to modify and debug.  Probably the only one that works on a reasonable budget/timeline.
    99+% of applications would probably not need the performance (at least initially) beyond what LV can deliver.  Even if you did, you'd be crazy not to start with the most straightforward.
    My personal bias is towards Measurement Studio.  I feel that it gives me the ability to get my hands dirty when necessary but maintain a very clean UI.  With LV I feel that there is some overhead when interfacing with external code.  If I already knew LV would I learn/buy Measurement Studio just for this application, almost certainly not.
    Don't let perfection be the enemy of the very, very good.  I say go with LV.
    End stream of consciousness.

  • What's the best way to implement an array on OOP?

    Hello,
    In the attached image, I do a database query with one query string. It opens the connection, makes the query, and closes the connection. The output array is scanned for certain conditions later.
    If I have 10 queries I could simply make an array of queries and make an array of replies. Then I could decompose the output array in a for loop and run my evaluations.
    In OOP however, I find myself wanting to make each query as an object, to encapsulate it. That is a problem though, because the database resides in a server in another building across town, and the connection to it is slow. So multiple queries take too long.
    How do I approach this in OOP?

    Or yet another approach...
    Use "Composition" pattern to say the connection is a part of the query and implement the connection class using the Singlton pattern.
    The Connection method that crates the connection would only make the connection when an open is invoked and the connection does not alreday exist.
    So your queries are an array like what seems natural (is that "Cohesion").
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Can anyone explain the array-binary implementation?

    Hi,
    i have a final exam tomorrow, and I got stuck on the array implementation of a binary tree, can anyone please provide me a code that implements the tree non recursively into an array, the book has a recursive code, which i tried to trace, but it got so deep and confusing. Can anyone please help?
    thanks :)
    Edited by: haraminoI on Apr 8, 2009 11:36 PM

    Melanie_Green wrote:
    haraminoI wrote:
    Hi,
    i have a final exam tomorrow, and I got stuck on the array implementation of a binary tree, can anyone please provide me a code that implements the tree non recursively into an array, the book has a recursive code, which i tried to trace, but it got so deep and confusing. Can anyone please help? Ehhh you could find an implementation online.
    Just remember given an array indexed from 0.
    Each indexes left child is (index*2+1), right child is (index*2+2).
    Each indexes parent is ((index-1)/2)
    Melthanks, i tried searching online, but i kept getting the recursive implementation.
    And now i see where to place the binary node and children values in the array, but how do I get the binary tree values from a sorted list in the frist place, thanks! :)

  • The Mysterious java array implementation

    In java when we create an array of primitive data type
    e.g long[] x = new long[10];
    we can reterieve the lenght of the array using x.length. Does someone know where this variable length is declared. As in java arrays are implemented as an Objects. Even i treid to find out the class reference variable "x" belongs to, and I came to know that it is "[J" and this class implements Cloneable and Seriaziable interface. But there is no field or variable like "length".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Java-Aspirant wrote:
    . Even i treid to find out the class reference variable "x" belongs to, and I came to know that it is "[J" and this class implements Cloneable and Seriaziable interface. But there is no field or variable like "length".
    If you want to use reflection on arrays, there's  [java.lang.reflect.Array|http://java.sun.com/javase/6/docs/api/java/lang/reflect/Array.html which allows you to interrogate the length pseudo-field and access elements.

  • How to implement large array in Dynamic programming

    Hi, there
    I am working on my dynamic pogramming codes using Java. The code is getting work, but the spead is very slow.
    It is supposed that the very long time run is due to the large array implementation in my codes. Most times, I have two double arrays size up to 320000, and one array of class the same size.
    Each iteration could take 30 minitues, the whole optimaization needs up to 50-100 iteration to get converged.
    Could any experise help me to how to improve the memory performance in Java?
    That is very important for my research.
    Looking for very quick response.
    Cheers
    Jack from Edinburgh

    An array of 320000 doubles isn't considered a large array. It must be
    somewhere in your algorithm implementation that slows down your
    process. Some relevant code snippets could clarify things ...
    kind regards,
    Jos

  • How an array implements an interface?

    Section 5.5 of JLS (dealing with casting conversions) explains something like this:
    When an interface type S is cast to an array type T,
    "then T must implement S, or a compile-time error occurs. "
    I could not understand how an array can be made to implement an interface.
    I guessed it means that the component type of array implements the interface, and prepared the following test code. It doesn't compile.
    interface S{  }
    class C implements S{ }
    class Test {
    public static void main(String[] args) {
         C[] ac = new C[100];
         S s = new C();
         C[] ac1 = (C[])s; //doesn't compile
         System.out.println(ac1.length);
    Would someone open my eyes? Thank you

    dmbdmb Your correction compiled my code. But I was not looking for that, because the corrected code casts an array type to array type. Anyway, thanks.
    jverdYou are the man. Now I got it. Thank you.
    I think I will have to remember your simplified rule (Then S must be Serializable or Cloneable) rather than the JLS' rule. With your rule, I can write a test code like this, which compiles, and which shows that an interface type can be cast to array type.
    import java.awt.Point;
    import java.io.Serializable;
    class Test {
            public static void main(String[] args) {
               Point[] pa = new Point[100]; //any array of reference type
               Serializable s = new String("test");
               Point[] pa1 = (Point[])s; //compiles, though invalid at runtime
    }

Maybe you are looking for