Help using arrays in java

HI all,
I am working on a program that will print out my initials 'A' and 'T' using arrays. I am asked to initialize the first intial to '*' and the second intial to '@'. I wrote the code but the output is wrong. Can someone help me by letting me know what I am doing wrong in my arrray?I just get back my array of 30X30. I also wrote a driver but when I run the program, I really appreciate it so much.
public class Initial
     private char whichinitial ;
     private int MAX =30;//Maximum amount for 2-d Matrix
     char[][] letterMatrix = new char[MAX][MAX];//2-d Array 30 x30
     private boolean first = true;
     public Initial()
     { //FIlls Array full of '*'s
          whichinitial = '*';
          for(int i=0;i< MAX;i++)
               for(int j=0;i< MAX;i++)
                    letterMatrix[i][j] = whichinitial;
     public void setLetter(char letter)
     {//Setter for Letter
           whichinitial = letter;
     public char getLetter()
     {//Getter for Letter
          return whichinitial;
     public void firstLetter()
     { //Creates an A shape
          for(int i=0;i< MAX;i++)
            for(int j=0;j< MAX;j++)
                  if((i>0)|| ((i<6) || ((j>0) && (j<29))))
                     letterMatrix[j] =whichinitial;
     public void secondLetter()
     {//Creates an T shape
          first = false;
               for(int i=0;i <MAX;i++)
               for(int j=0;j <MAX;j++)
                    if((i>1) ||(j < 29)||(j>5)||(i>10))
                         letterMatrix[i][j] = whichinitial;
     public void display()
     {//Displays the Initials
          if(first)
               System.out.println("\n \n \n My First Initial," + whichinitial + ", follows:");
          else
               System.out.println("\n \n \n My Last Initial," + whichinitial + ", follows:");
               for(int i=0;i <MAX;i++)
                    System.out.println();
                    for(int j=0;j <MAX;j++)
                         if(letterMatrix[i][j] == '*')
                              System.out.print(" ");
                         else
                              System.out.print(letterMatrix[i][j]);

I am trying to write a program using a matrix. The size of the maxtrix should be 30X30. The first initial shoulld be initialized to '*' and the secind initial should be initialized to '@'. Both initials should be 30 characters high and 30 characters wide and the initials should also represent the uppercase letter of your initials. I know that the first initial's matrix needs to be filled up vertically and the second initial needs to be filled horizontally but the output is wrong....PLease Help!
Message was edited by:
apples03

Similar Messages

  • Using arrays in JAVA

    Hi Guys,
    I always had a few problems using arrays and now I need to use them and I am stuck.
    on my program i need to create an array of int with the numbers 1 to 1000 in it for this I have done:
    int[ ] array;
    on the class constructor
    array = new int[1000];
    to fill the array:
    for (int i = 0; i < array.length; i++)
         array[i] = i;
    The problem is that I always get an ArrayIndexOutOfBoundsException error.
    I know how to solve it which is to create an array with 1001 elements but is there a more elegant way of creating the array or this is the way to do it?
    To put my question in another way if any of you Guys was creating this program which way would you do it.
    Best regards
              Luis

    Sloppy of me. This is a bit better:
    package cruft;
    import java.util.Arrays;
    * A class for a one-based array of ints.
    public class OneBasedIntArray
       private int [] values;
       public static void main(String[] args)
          int [] values = new int[args.length];
          for (int i = 0; i < args.length; i++)
             values[i] = Integer.parseInt(args);
    OneBasedIntArray intArray = new OneBasedIntArray(values);
    System.out.println(intArray);
    public OneBasedIntArray(int[] values)
    this.values = new int[values.length];
    System.arraycopy(values, 0, this.values, 0, values.length);
    public int getValue(int index)
    if (index <= 0)
    throw new IllegalArgumentException("this array is one-based");
    return values[index-1];
    public void setValue(int index, int value)
    if (index <= 0)
    throw new IllegalArgumentException("this array is one-based");
    this.values[index-1] = value;
    public boolean equals(Object o)
    if (this == o)
    return true;
    if (o == null || getClass() != o.getClass())
    return false;
    OneBasedIntArray intArray = (OneBasedIntArray) o;
    if (!Arrays.equals(values, intArray.values))
    return false;
    return true;
    public int hashCode()
    return (values != null ? Arrays.hashCode(values) : 0);
    public String toString()
    StringBuilder builder = new StringBuilder();
    builder.append("OneBasedIntArray{");
    for (int i = 0; i < values.length; i++)
    builder.append("(").append(i+1).append(",").append(values[i]).append(")");
    builder.append('}');
    return builder.toString();

  • Tic Tac Toe help using array

    Ok i am trying to get a tic tac toe game, which uses array. I need to get 3 buttons and store them then i can check those numbers to see if its a win. Here is my code
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int map[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i< c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String args[] )
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    I couldn't try this out due to a few syntax errors, so fixed some. Now the buttons seem to work.
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int c[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
    private int flag;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3=0;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i < c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String[] args)
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

  • Help using InputMethod in Java

    I would like to get the input from the user into a JTextField using a InputMethod.
    There are 2 JTextFields in the gui. One takes input in the native language say "Hindi" from India. and the other just takes input in english. The english one is fine. But I want to somehow set the property of the JTextField so that the input is unicode and as specified by the input method.
    Is there any way to do it, rather than the having the client to change it manually.

    Try:
        getInputContext().selectInputMethod(localeSupportedByIM);

  • Re: Beginner needs help using a array of class objects, and quick

    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ? In html, I assume. How did you generate the html code of your three classes ? By help of your IDE ? NetBeans ? References ?
    I already posted my question with six source code classes ... in text mode --> Awful : See "Polymorphism did you say ?"
    Is there a way to discard and replace a post (with html source code) in the Sun forum ?
    Thanks for your help.
    Chavada

    chavada wrote:
    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.You think she's still around almost a year later?
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ?Just use [code] and [/code] around it, or use the CODE button
    [code]
    public class Foo() {
      * This is the bar method
      public void bar() {
        // do stuff
    }[/code]

  • Help writing a prog using array

    This would be my first try in using array how would I write this in Java using array: Any suggestions?
    How many numbers will you enter?
    4
    Enter 4 integers one per line:
    2
    1
    1
    2
    the sum is 6.
    The numbers are:
    2 33.3333% of the sum
    1 16.6666% of the sum
    1 16.6666% of the sum
    2 33.3333% of the sum

    Here's a starter for printing out the sums..
        int[] array;
        // INSERT CODE TO READ NUMBERS INTO THE ARRAY HERE.
        // find the sum
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += array[0];
        System.out.println("the sum is " + sum);
        System.out.println("The numbers are:");
        // print the numbers
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i] + " " +
                               (100.0*array/sum) + " of the sum");

  • Example of passing String Array from java to C using JNI

    hi all
    i searched net for passing string array from java to C but i dont get anything relevent
    i have
    class stu
    int rollno
    string name
    String [] sub
    i want to pass all as String array from java to C and access it C side

    1. Code it as though it were being passed to another method written in java.
    2. Redefine the method implementation to say "native".
    3. Run jnih to generate a C ".h" file. You will see that the string array
    is passed into C as a jobject, which can be cast to a JNI array.
    4. Write the C code to implement the method and meet the interface
    in the generated .h file.

  • Require help on Array of Nested tables and Oracle Object type

    Hi All,
    I have a scenario where I have some millions of records received from a flat file and the record is stored in Table as below:
    Tablename: FILE_RECORD
    Rows:
    FILE_REG_ID = 1
    RECORD_NBR = 1     
    PROCESSED_IND = U
    RECORD= 00120130326006A
    FILE_REG_ID = 1
    RECORD_NBR = 2     
    PROCESSED_IND = U
    RECORD= 00120130326003
    1) I have to read these records at once and
    a) Split the RECORD column to get various other data Eg: Fld1=001, Fld2=20130326, Fld3 = 003
    b) send as an Array to Java.
    2) Java will format this into XML and sent to other application.
    3) The other application returns a response as Successful or Failure to Java in XML
    4) Java will send RECORD_NBR and the corresponding response as Success or Failure back to PLSQL
    5) PLSQL should match the RECORD_NBR and update the PROCESSED_IND = P.
    I 'm able to achieve this using SQL Table type by creating a TYPE for Each of the fields (Flds) however the problem is Java cannot Access the parameters as the TYPE are of COLUMN Types
    Eg: For RECORD_NBR
    SUBTYPE t_record_nbr IS FILE_RECORD.T010_RECORD_NBR%TYPE;
    Can you please let me know how I can achieve this to support Java, I know one way that is by creating an OBJECT TYPE and a TABLE of the OBJECT TYPE.
    Eg: T_FILE_RECORD_REC IS OBJECT
    FILE_REG_ID number(8), RECORD_NBR number (10), PROCESSED_IND varchar2(1), RECORD varchar(20)
    Create type T_FILE_RECORD_TAB IS TABLE OF T_FILE_RECORD_REC
    However I'm facing a problem to populate an Array of records, I know I'm missing something important. Hence please help.
    It would be helpful to provide some guidelines and suggestions or Pseudo or a Code to achieve this. Rest all I can take up further.
    Thanks in advance,

    I know once way that is creating a OBJECT TYPE and a TABLE of OBJECT TYPE, howeve I feel I'm missing something to achieve this.You're right, you need SQL object types created at the database level. Java doesn't know about locally defined PL/SQL types
    However you can do without all this by creating the XML directly in PL/SQL (steps 1+2) and passing the document to Java as XMLType or CLOB.
    Are you processing the records one at a time?

  • How to pass Array of Java objects to Callable statement

    Hi ,
    I need to know how can I pass an array of objects to PL/SQL stored procedure using callable statement.
    So I am having and array list of some object say xyz which has two attributes string and double type.
    Now I need to pass this to a PL/SQL Procedure as IN parameter.
    Now I have gone through some documentation for the same and found that we can use ArrayDescriptor tp create array (java.sql.ARRAY).
    And we will use a record type from SQL to map this to our array of java objects.
    So my question is how this mapping of java object's two attribute will be done to the TYPE in SQL? can we also pass this array as a package Table?
    Please help
    Thanks

    I seem to remember that that is in one of Oracle's online sample programs.
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/index.html

  • Using Arrays in a program

    First, I would like to thank everyone in this forum for all the help they have given me over the past few weeks. With that said, I am currently trying to alter the following code to accept and use arrays to end to produce three seperate results. The program now as three hard coded variables which are
    Amount = 200000.00;
    Term = 30;
    InterestRate = .0575;
    I need to have the program work the same, but produce results for three different Terms and Three different periods. Below is the code the I am working on, I have added two arrays containing the required information. I am having a hard time coming up with a for statment to move the program through the two arrays. Any pushes in the right direction would be great. I left the hard code variable in place, I know that I do need to remove them and alter the equations. I just thought it would be easier for everyone to understand if I left the code in working form.
    import java.math.*;
    import java.text.*;
    import java.util.*;
    // The Payment class displays a predetermined monthly mortgage payment
    public class Payment
         public static void main(String[]arguments)
              //Creates Two Arrays for InterestRates and Terms
              double[] InterestRates = {.0535, .055, .0575};
              int[] Terms = {7, 15, 30};
              //Creates variables
              double Amount;
              int Term;
              double InterestRate;
              //Assigns values to variables
              Amount = 200000.00;
              Term = 30;
              InterestRate = .0575;
              //Alters the display format of Amount variable
              NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
              String s = n.format(Amount);
              //Creates variables
              double MonthlyInterestRate;
              int TotalMonths;
              double Payment;
              //Assigns values to variables
              MonthlyInterestRate = InterestRate / 12;
              TotalMonths = Term * 12;
              Payment = Amount* MonthlyInterestRate / (1-(Math.pow((1+MonthlyInterestRate ),(-TotalMonths))));
              //Takes Payment variable and round answer to 2 decimal points
              BigDecimal bd = new BigDecimal(Payment);
    bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
              //Instructions to display various varibles
              System.out.println("Cost of Mortgage "+ s);
              System.out.println("Length of Term " + Term);
              System.out.println("Interest Rate 5.75% ");
              System.out.println("The monthly payment of this loan is $" + bd);
              System.out.println();
              //Creates new set of variables
              double MonthlyInterest;
              double MonthlyPrincipal;
              double TotalInterestPaid;
              int NumberofPayments;
              //Creates Balance variable
              double Balance;
              //Initialization of Balance variable
              Balance = 200000;
              TotalInterestPaid = 0;
              NumberofPayments = 360;
              //Creates a loop that calculates the entire term of loan
              do
              MonthlyInterest = Balance * (InterestRate / 12);
              MonthlyPrincipal = Payment - MonthlyInterest;
              Balance = Balance - MonthlyPrincipal;
              TotalInterestPaid = TotalInterestPaid + MonthlyInterest;
              NumberofPayments = NumberofPayments - 1;
              //Takes current balance and rounds the answer to two digits
              BigDecimal bb = new BigDecimal(Balance);
    bb = bb.setScale(2, BigDecimal.ROUND_DOWN);
              BigDecimal tip = new BigDecimal(TotalInterestPaid);
                        tip = tip.setScale(2, BigDecimal.ROUND_UP);
              System.out.println("New Loan Balance " + bb);
              System.out.println();
              System.out.println("Total Interest Paid " + tip);
              System.out.println();
              System.out.println("Number of Payments remaining " + NumberofPayments);
              System.out.println();
              //The following lines of code pauses the loop to allow the user to read the output
              //The speed of th display can be adujusted to a wide variety of speeds
              try
                   Thread.sleep(400);
                   catch (InterruptedException exc)
              //Loop condition
              while (NumberofPayments > 0);
    //Ends Application

    Try this. It should give you some ideas. :)
    import java.math.BigDecimal;
    import java.text.NumberFormat;
    import java.util.Locale;
    // The Payment class displays a predetermined monthly mortgage payment
    public class Payment {
        public static final NumberFormat CURRENCY_FORMAT = NumberFormat.getCurrencyInstance(Locale.US);
        public static final double[] INTEREST_RATES = {.0535D, .055D, .0575D};
        public static final int[] TERMS = {7, 15, 30};
        public static final double AMOUNT = 200000.00;
        public static final int MONTHS_PER_YEAR = 12;
        public static void main(String[] arguments) {
            for (int t = 0; t < TERMS.length; t++) {
                for (int i = 0; i < INTEREST_RATES.length; i++) {
                    displayPayments(AMOUNT, INTEREST_RATES, TERMS[t]);
    private static void displayPayments(double amount, double interestRate, int term) {
    //Creates variables
    //Assigns values to variables
    double monthlyInterestRate = interestRate / MONTHS_PER_YEAR;
    int totalMonths = term * MONTHS_PER_YEAR;
    double payment = amount * monthlyInterestRate / (1 - Math.pow(1 + monthlyInterestRate, -totalMonths));
    //Instructions to display various varibles
    System.out.println("Cost of Mortgage " + CURRENCY_FORMAT.format(amount));
    System.out.println("Length of Term " + term);
    System.out.println("Interest Rate " + new BigDecimal(interestRate * 100).setScale(2, BigDecimal.ROUND_HALF_UP) + '%');
    System.out.println("The monthly payment of this loan is " + CURRENCY_FORMAT.format(payment));
    System.out.println();
    //Creates new set of variables
    double totalInterestPaid = 0.0D;
    //Creates balance variable, Initialization of balance variable
    double balance = amount;
    //Creates a loop that calculates the entire term of loan
    System.out.println("New Loan balance, Total Interest Paid, Number of Payments remaining");
    for (int numberofPayment = totalMonths; numberofPayment > 0; numberofPayment--) {
    double monthlyInterest = balance * monthlyInterestRate;
    double monthlyPrincipal = payment - monthlyInterest;
    balance -= monthlyPrincipal;
    totalInterestPaid += monthlyInterest;
    //Takes current balance and rounds the answer to two digits
    BigDecimal bb = new BigDecimal(balance);
    bb = bb.setScale(2, BigDecimal.ROUND_DOWN);
    BigDecimal tip = new BigDecimal(totalInterestPaid);
    tip = tip.setScale(2, BigDecimal.ROUND_UP);
    System.out.println(CURRENCY_FORMAT.format(bb.doubleValue()) + ", " +
    CURRENCY_FORMAT.format(tip.doubleValue()) + ", " +
    numberofPayment);
    System.out.println();
    //Ends Application

  • Passing Array of java objects to and from oracle database-Complete Example

    Hi all ,
    I am posting a working example of Passing Array of java objects to and from oracle database . I have struggled a lot to get it working and since finally its working , postinmg it here so that it coudl be helpful to the rest of the folks.
    First thinsg first
    i) Create a Java Value Object which you want to pass .
    create or replace and compile java source named Person as
    import java.sql.*;
    import java.io.*;
    public class Person implements SQLData
    private String sql_type = "PERSON_T";
    public int person_id;
    public String person_name;
    public Person () {}
    public String getSQLTypeName() throws SQLException { return sql_type; }
    public void readSQL(SQLInput stream, String typeName) throws SQLException
    sql_type = typeName;
    person_id = stream.readInt();
    person_name = stream.readString();
    public void writeSQL(SQLOutput stream) throws SQLException
    stream.writeInt (person_id);
    stream.writeString (person_name);
    ii) Once you created a Java class compile this class in sql plus. Just Copy paste and run it in SQL .
    you should see a message called "Java created."
    iii) Now create your object Types
    CREATE TYPE person_t AS OBJECT
    EXTERNAL NAME 'Person' LANGUAGE JAVA
    USING SQLData (
    person_id NUMBER(9) EXTERNAL NAME 'person_id',
    person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
    iv) Now create a table of Objects
    CREATE TYPE person_tab IS TABLE OF person_t;
    v) Now create your procedure . Ensure that you create dummy table called "person_test" for loggiing values.
    create or replace
    procedure give_me_an_array( p_array in person_tab,p_arrayout out person_tab)
    as
    l_person_id Number;
    l_person_name Varchar2(200);
    l_person person_t;
    l_p_arrayout person_tab;
    errm Varchar2(2000);
    begin
         l_p_arrayout := person_tab();
    for i in 1 .. p_array.count
    loop
         l_p_arrayout.extend;
         insert into person_test values(p_array(i).person_id, 'in Record '||p_array(i).person_name);
         l_person_id := p_array(i).person_id;
         l_person_name := p_array(i).person_name;
         l_person := person_t(null,null);
         l_person.person_id := l_person_id + 5;
         l_person.person_name := 'Out Record ' ||l_person_name ;
         l_p_arrayout(i) := l_person;
    end loop;
    p_arrayout := l_p_arrayout;
         l_person_id := p_arrayout.count;
    for i in 1 .. p_arrayout.count
    loop
    insert into person_test values(l_person_id, p_arrayout(i).person_name);
    end loop;
    commit;
    EXCEPTION WHEN OTHERS THEN
         errm := SQLERRM;
         insert into person_test values(-1, errm);
         commit;
    end;
    vi) Now finally create your java class which will invoke the pl/sql procedure and get the updated value array and then display it on your screen>Alternatively you can also check the "person_test" tbale
    import java.util.Date;
    import java.io.*;
    import java.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.driver.*;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    public class ArrayDemo
    public static void passArray() throws SQLException
    Connection conn = getConnection();
    ArrayDemo a = new ArrayDemo();
    Person pn1 = new Person();
    pn1.person_id = 1;
    pn1.person_name = "SunilKumar";
    Person pn2 = new Person();
    pn2.person_id = 2;
    pn2.person_name = "Superb";
    Person pn3 = new Person();
    pn3.person_id = 31;
    pn3.person_name = "Outstanding";
    Person[] P_arr = {pn1, pn2, pn3};
    Person[] P_arr_out = new Person[3];
    ArrayDescriptor descriptor =
    ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );
    ARRAY array_to_pass =
    new ARRAY( descriptor, conn, P_arr);
    OracleCallableStatement ps =
    (OracleCallableStatement )conn.prepareCall
    ( "begin give_me_an_array(?,?); end;" );
    ps.setARRAY( 1, array_to_pass );
         ps.registerOutParameter( 2, OracleTypes.ARRAY,"PERSON_TAB" );
         ps.execute();
         oracle.sql.ARRAY returnArray = (oracle.sql.ARRAY)ps.getArray(2);
    Object[] personDetails = (Object[]) returnArray.getArray();
    Person person_record = new Person();
    for (int i = 0; i < personDetails.length; i++) {
              person_record = (Person)personDetails;
              System.out.println( "row " + i + " = '" + person_record.person_name +"'" );
                        public static void main (String args[]){
         try
                             ArrayDemo tfc = new ArrayDemo();
                             tfc.passArray();
         catch(Exception e) {
                        e.printStackTrace();
              public static Connection getConnection() {
         try
                             Class.forName ("oracle.jdbc.OracleDriver");
                             return DriverManager.getConnection("jdbc:oracle:thin:@<<HostNanem>>:1523:VIS",
                             "username", "password");
         catch(Exception SQLe) {
                        System.out.println("IN EXCEPTION BLOCK ");
                        return null;
    and thats it. you are done.
    Hope it atleast helps people to get started. Comments are appreciated. I can be reached at ([email protected]) or [email protected]
    Thanks
    Sunil.s

    Hi Sunil,
    I've a similar situation where I'm trying to insert Java objects in db using bulk insert. My issue is with performance for which I've created a new thread.
    http://forum.java.sun.com/thread.jspa?threadID=5270260&tstart=30
    I ran into your code and looked into it. You've used the Person object array and directly passing it to the oracle.sql.ARRAY constructor. Just curios if this works, cos my understanding is that you need to create a oracle.sql.STRUCT out of ur java object collection and pass it to the ARRAY constructor. I tried ur way but got this runtime exception.
    java.sql.SQLException: Fail to convert to internal representation: JavaBulkInsertNew$Option@10bbf9e
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatum(OracleTypeADT.java:239)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatumArray(OracleTypeADT.java:274)
                        at oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(OracleTypeUPT.java:115)
                        at oracle.sql.ArrayDescriptor.toOracleArray(ArrayDescriptor.java:1314)
                        at oracle.sql.ARRAY.<init>(ARRAY.java:152)
                        at JavaBulkInsertNew.main(JavaBulkInsertNew.java:76)
    Here's a code snippet I used :
    Object optionVal[] =   {optionArr[0]};   // optionArr[0] is an Option object which has three properties
    oracle.sql.ArrayDescriptor empArrayDescriptor = oracle.sql.ArrayDescriptor.createDescriptor("TT_EMP_TEST",conn);
    ARRAY empArray = new ARRAY(empArrayDescriptor,conn,optionVal);If you visit my thread, u'll see that I'm using STRUCT and then pass it to the ARRAY constructor, which works well, except for the performance issue.
    I'll appreciate if you can provide some information.
    Regards,
    Shamik

  • How to use array?I am a newer   ------:(

    In C language I can use array this way:
    char array[10][20];
    fread(array[1],20,1,fp);
    but in java,what to do?
    char array[][]=new [10][20];
    and the code below will cause an error:
    binstream.read(array[1]);//error line
    pls help me and tell me what to do,thank you very much

    Hi evilstar007!
    1st) There aren't unsigned primitives in Java, all primitives are signed.
    2nd) The loop in previous message will read an entire line filling the buffer without length contraints. If there are n^z then it will read n^z "chars". This is is for text but I know there is a special one as you need, for bytes (primitive byte). You can also retrieve the bytes from stream:
    data = new byte[dim];
    inp.read(data);
    I'm not sure about, there are a lot of methods and classes.
    You pretend to read from stream and fill the contents of RomBanks array with length 32768L ok ?
    Read the entire line and retrieve bytes.
    Since you are a C programmer will be easy to understand Java.
    Best Regards!

  • Help with Array of Arrays

    import java.util.Arrays;
    import java.util.Date;
    import java.util.List;
    public class StockDay
        private String[] stockDayData;
        List stockDays = new ArrayList();
        public StockDay(String stockData)
            stockDayData = new String[6];
            String[] stockDayData= stockData.split(",");
            stockDays.add(stockDayData[]);
    }I have an outside class calling this class with a string of data separated by commas. I am trying to separate the data so that each time the method is called, each piece of the data (6 total) is put into an array list. Then that array list is put into an array list of arrays. I am sorry if I have not made this clear, I will try again. I want an array of arrays, and the interior arrays will contain 6 pieces of information each from the string that is given to the method, and each separated by commas.
    Any help is much appreciated. I am also curious how I can accesses one piece of the data at a time, this is what I am thinking for this:
    data = arraylist1[#].arraylist2[#]this would set data equal to whatever is in arraylist2[#]
    Thank you very much.

    ActingRude wrote:
    I meant just a simple Array I guess.Note the difference between Array and array. Class names start with uppercase in java. There is a class called Array, but it's just a utility class, and isn't part of arrays.
    .. like I am using above? I was under the impression that the biggest syntax difference between an array(fixed number of items) and an ArrayList(unfixed number of items) was the use of the [] and () That's one of many syntactical differences, yes, but the main difference is not in the syntax. arrays are part of the Java language, have special handling because of that, and are faster and smaller than ArrayLists. ArrayList is part of the API, and didn't exist until Java 1.2 (about 5-6 years into Java's life, I think), and is built on top of an array.
    UnsupportedOperationException:
    null (in java.util.AbstractList)I have no idea what is causing this, I can only assume that I am doing something wrong...It looks like you're tyring to add null to an ArrayList and it doesn't like it. I thought ArrayList accepted null elements, but I could be wrong. Paste in the exact line that's causing it, and any declarations necessary to clarify any variables used on that line.

  • Help Sorting array of strings with numbers in them

    Hello I need to sort an array of Strings of numbers. The order is not what I want it to be. instead of 1, 5, 20 it will go 1, 20, 5.
    I did a google search for this and found some code that could fix this. The only problem is I tried using it as a method in my program and am getting a compile-time error that I'm not sure how to fix.
    C:\Documents and Settings\Owner\Desktop\stringcompare.java:18: '(' or '[' expected
                new Comparator<String>()
                                    ^I'm not sure what to do here. Any help would appreciated.

    import java.io.*;
    class MyProgram{
    //This is my old bubble sort method which screws up with numbers
    public static String[] sort( String[] points)
              boolean keepGoing = true;
              while(keepGoing == true){
                   keepGoing = false;
                   for(int i = 0; i < points.length - 1; i ++)
                        if(points.compareToIgnoreCase(points[i + 1]) < 0)
                             String temp = points[i];
                             points[i] = points[i + 1];
                             points[i + 1] = temp;
                             keepGoing = true;
              return points;
    //This method reads a pre-existing text file
    public static String[] readPoints() throws IOException
              FileReader file = new FileReader("points.txt");     
              BufferedReader in = new BufferedReader(file);
              String temp;                
              String[] list = new String[100];     
              int i = 0;
              while (i < list.length)                    
                   temp = in.readLine();
                   if (temp != null)
                        list[i] = temp;                    
                   else
                        list[i] = " ";
                   i++;
              in.close();                              
              return list;
    //rewrites file after being sorted
         public static void savePoints(String[] points) throws IOException
              FileWriter file = new FileWriter("points.txt");
              BufferedWriter out = new BufferedWriter(file);
              int i = 0;
              while (i < points.length)          // while the end of file is not reached
                   out.write(points[i]) ;
                   out.newLine();
                   i++;
              out.flush();
              out.close();
    public static void main(String[]args) throws Exception{
    String[]points = new String [100];
    points = readPoints();
    points = sort(points);
    savePoints(points);
    for(int i = 0; i < points.length - 1; i++)
    System.out.println(points[i]);
    The problem is that it doesn't sort as I would like it and I'm not sure how to get the comparator to work properly.
    Edited by: myol on May 31, 2008 4:21 PM
    Edited by: myol on May 31, 2008 4:23 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help with Arrays

    hi, ive just started a java course about a month ago and am having trouble with an assignment (big trouble), basicly I was wondering if someone could help me in this program I am reading from a text file and trying to store the info in a 2d array the text file has 60 lines like this :
    1     Y1     -9.30     5.65     -5.02
    and my code is:
    public static String [][] readfile (String fileName)
              /*declare local variables*/
              String [][]data;
              String [] line;
              String [] temp;
              String token;
              int count = 0;
              String inputLine;
              data = new String[60][count];     
         try
                           /*try loop to catch exceptions*/               
              FileReader reader = new FileReader("Data_Set_1.txt");
              /*file name to be filled in above*/
              BufferedReader in = new BufferedReader(reader);
              boolean done = false;
              while(!done)
                   inputLine = in.readLine();
    /*readline() will return null and exit this loop at the end of a line*/
              if (inputLine == null)
                   done = true;
                   break;
    /*break the string up declare tokeniser and pass it the inputLine string*/
    StringTokenizer tokeniser = new StringTokenizer(inputLine);
    token = tokeniser.nextToken();/*this will need to be moved but where*/
                   temp = new String [count];
                   count++;
                   while (tokeniser.hasMoreTokens())
    /*tokeniser will return true if there is more file to be read */
                    for (int i = 0;i < count;i++)
                    temp[i] = token;     
                    }/*end for*/               
                   }/*while*/
                   for (int j=0;j <temp.length;j++)
                        line[j] = temp[j];
              }/*end outer while*/
              for (int genes = 0;genes < 59;genes++)
              {for (int col = 0;col < 5;col++)
              data[genes][col] = line[genes], line[col];
              }/*end inner for*/
         }/*end outer for*/
    }/*end try*/I left out the catch loop as it not relevant. I know that the line:
    data[genes][col] = line[genes], line[col];
    is wrong but I dont know how to fix it and cant find the answer anywhere, if anyone can spot any other mistakes it would be great to let me know and im sorry if Ive posted wrong or anything like that ill fix it next time, any help or comments would be much appreciated.
    Thanks

    No need to apologise for being new to Java. After all, that is what the forum is for! If you wanted to apologise about your nickname well.... it'll do. :-)
    Your thinking is right. However do give gimbal2's idea a little thought. I do not know what each row is storing but if the data for each row were in an object, then the object could use meaningful names and provide sensible formatting and so on. However I have not seen the details of the assignment that your teacher gave you so it may have to be arrays. But what you would have would be an array of object called LineData or Genes. You might cycle through the array asking each object to call out its name and a feature for example.
    In general you gain very little advantage by passing a "temp" array to another array "line" using an equals sign. The reason is that there is only one array it just has two names! A bit like pinning an extra registration plate on a car! If you really wanted two arrays you would have to investigate "cloning" of arrays. However if you add the temp array (or whatever you call it) to another array such as your two dimensional array, then you can re-use the temp name by applying "=new" to create a new array. This will not affect the existing "array within an array" because it no longer needs a name - it is located by a number now!!!
    Array[] is fast in Java but you have to give it a size before you can use it. Arraylist is less fast but has the ability to grow. Not that the speed difference will be at all noticeable. Actually the internal working of the Arraylist uses arrays and cloning and such like.
    thesonofdad has given some good code. Again I might consider putting it in gimbal2's object though.
    I have covered quite a lot of ground so feel free to ask questions.

Maybe you are looking for