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();

Similar Messages

  • 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

  • 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.

  • 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

  • Using array with a stored procedure

    Hello,
    In order to transmit an array from java to a PL/SQL procedure with oracle8i, we have been trying to instanciate an javaArrayDescriptor using the name of an oracle user Datatype (a table of Varchar(20)).
    This works perfectly well while connected to the database as the owner of the datatype (user 1),
    but doesn't when connected with another user (user 2) even if a public synonym is created.
    As it seemed that synonym for objects do not work properly, we tried to put the datatype as part of a public package.
    This works when the procedure is called from SQL worksheet (connected with user 2) but doesn't when it is called from our java application (still connected with user 2).
    We also created the same datatype for user 2. However the procedure (created by user 1) did not accept the new datatype (error: wrong type or number of arguments) as it requires the user 1 datatype.
    Is there a way to allow any user to use a datatype?
    Or to access a datatype defined in a package fom java in order to make an ArrayDescriptor?

    You should create the TYPE AddrType in Oracle (say thru Sql*Plus) using CREATE TYPE.. command. Currently, looks like you have the TYPE declared within a package.

  • Error using Arrays.toString()

    Hi there,
    I am getting the following error using Arrays.toString on a String Array. 'toString() in java.lang.Object cannot be applied to (java.lang.String[]).
    The line in question is at the bottom of the below code. It starts 'rtitem.appendText.....
    import lotus.domino.*;
    //import java.util.Arrays;
    public class JavaAgent extends AgentBase {
         Database curDb;
         String[] dbList;
         public void NotesMain() {
         int dbcount = 0;
              try {
                   Session session = getSession();
                   AgentContext agentContext = session.getAgentContext();
                   //get current database
                   Database curDb = agentContext.getCurrentDatabase();
                   //build a list of servers;
                   String[] servers = {"Norwich002/Norwich/MoneyCentre","Norwich003/MoneyCentre","Norwich004/MoneyCentre","Norwich005/MoneyCentre","Norwich007/Norwich/MoneyCentre","Norwich008/Norwich/MoneyCentre","Norwich010/Norwich/MoneyCentre","Norwich020/Norwich/MoneyCentre","Norwich021/Norwich/MoneyCentre"};
                   //loop through server list
                   int arraylen = servers.length;
                   for(int i=0;i <= arraylen;i++){
                        //create a notesdbdirectory collection for the current server iteration
                        DbDirectory dbdir = session.getDbDirectory(servers);
                        //get first database
                        Database db = dbdir.getFirstDatabase(DbDirectory.DATABASE);
                        //loop through databases in dbdir
                        while (db != null){
                             //add database details to our list
                             dbList[dbcount] = db.getTitle() + " - " + db.getFilePath();
                             dbcount++;     
              } catch(Exception e) {
                   e.printStackTrace();
              private boolean sendEmail(String subject){
                   try{
                        Document mailDoc = curDb.createDocument();
                        mailDoc.replaceItemValue("SendTo","Hayleigh S Mann/Norwich/MoneyCentre");
                        mailDoc.replaceItemValue("Subject",subject);
                        RichTextItem rtitem = mailDoc.createRichTextItem("Body");
                        rtitem.appendText(java.util.Arrays.toString(dbList));
                        mailDoc.send();
                        return true;
                   }catch(Exception e){
                        e.printStackTrace();
                        return false;

    No, that doesn't make any sense. Arrays.toString can take any array as an arg: [http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#toString(java.lang.Object[])]
    import java.util.*;
    public class A {
      public static void main(String[] args) {
        String str = Arrays.toString(args);
        System.out.println(str);
    :; java -cp . A abc 123 xxx
    [abc, 123, xxx]

  • 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 of Point Class

    I use Point class as array. I already create that. However I can't access to setLocation.
    Ex.
    Point myPoint[] = new Point[10];
    myPoint[0].setLocation(10, 2);
    It has a error.
    Please Explain me.

    DeltaGeek wrote:
    BalusC wrote:
    Or use [Arrays#fill()|http://java.sun.com/javase/6/docs/api/java/util/Arrays.html]. Point[] points = new Point[10];
    Arrays.fill(points, new Point());
    That doesn't do what you think it does, unless you want your array to contain 10 references to the same Point object.The OP has received a good answer, I believe. So it's worth risking diverting this thread into the weeds by pointing out that if Java had closures then BalusC's code could be modified to work.

  • 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!

  • Using array create JLabel

    i have one problem about using addKeyListener, i'm using array to create JLabel but once i've compile it, it came out a message as i shown, so where is my problem, hope someone can fix it for me and explain it for me, thank you
    ---------- Capture Output ----------
    "C:\Program Files\Java\jdk1.6.0_03\bin\javac.exe" Login.javaLogin.java:78: not a statement
    inputTextName[1]KeyPressed( event );
    ^
    Login.java:78: ';' expected
    inputTextName[1]KeyPressed( event );
    ^
    2 errors
    Terminated with exit code 1.---------- Capture Output ----------
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Login extends JFrame
         //JLabel[] lblName = {"lblName1","lblName2"};
         JLabel[] labelName;
         //JTextField[] txtfldName = {input1,input2};
         JTextField[] inputTextName;
         //JLabel[] array = new JLabel[veryLargeNumber];
         JButton[] btnName = new JButton[3];
    public void userInterface()
         this.setBackground(Color.blue);
         this.setTitle("Log in");
         this.setSize(285,130);
         this.setVisible(true);
         Container contentPane = getContentPane();
         contentPane.setLayout(null);
         labelName[0] = new JLabel();
         labelName[0].setText("ID: ");
         labelName[0].setBounds(16, 16, 130, 21);
         this.add(labelName[0]);     
         inputTextName[0] = new JTextField();
         inputTextName[0].setText(" ");
         inputTextName[0].setBounds(50, 16, 150, 21);
         inputTextName[0].setHorizontalAlignment(JTextField.LEFT);
         this.add(inputTextName[0]);
         labelName[1] = new JLabel();
         labelName[1].setText("Password: ");
         labelName[1].setBounds(16, 48, 104, 21);
         this.add(labelName[1]);
         inputTextName[1] = new JTextField();
         inputTextName[1].setText(" ");
         inputTextName[1].setBounds(50, 48, 150, 21);
         inputTextName[1].setHorizontalAlignment(JTextField.LEFT);
         this.add(inputTextName[1]);
         btnName[0] = new JButton();
         btnName[0].setText("login");
         btnName[0].setBounds(120,80,65,20);
         this.add(btnName[0]);
         btnName[1] = new JButton();
         btnName[1].setText("exit");
         btnName[1].setBounds(190,80,65,20);
         this.add(btnName[1]);
         inputTextName[1].addKeyListener(
             new KeyAdapter() // anonymous inner class
                // method called when user types in cartonsJTextField
                public void keyPressed( KeyEvent event )
                  inputTextName[1]KeyPressed( event );
             } // end anonymous inner class
          ); // end call to addKeyListener
    //call function
         public Login()
              userInterface();          
         public static void main (String args[])
              Login application = new Login();
               application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         }Edited by: slamgundam on Oct 24, 2007 11:48 PM

    slamgundam wrote:
    the purpose is try to get the text in the inputTextField
    inputTextName[1].addKeyListener(
        new KeyAdapter()
             // method called when user types in cartonsJTextField
             public void keyPressed( KeyEvent event )
                   String str = inputTextName[1].getText();
                   System.out.println(str);
    );

  • Import PHP-Array into Java-Application

    Hi!
    I want to call a PHP-Script from inside my Java-Application. The PHP-Script can return an array.
    How do I use a PHP-Array in Java and how do I import it????
    Thanks! =)

    thanks! =D
    one last question:
    -how would i have to change my example to make a
    https-connection?
    Did you try
    URL theURL = new URL("https://www.mysite.com/myscript.php");It works that simply. The only complication is if your server is set up for https or not. This is an Apache (or whatever webserver you are using)problem not a PHP problem.
    I think it gets upset if you try and use certificates with problems (self-signed etc) but not having tried this (I have only used it with certificates that are otherwise trustable) I don't know that for sure.
    Once upon a time I asked a question about using https as a client in Java and I got a variety of answers including doing mystic stuff with my keystore but I tried the simple and obvious and it works like a charm. At least from an Applet but I see no reason an application won't work the same way.
    Anyway try the simple and easy and see if that works for you. You might find that it does.

  • Convert javascript array to java array

    Is there any way possible to convert javascript array to java array?

    if you will try to experiment a javascript array
    putting it to a hidden element, it will be converted
    to a string (comma delimited). You can get the value
    of that element as a string and use StringTokenizer
    class to put the values into a java arrayThanks, got it.

  • Question about using arrays

    I have a web page written with combination of Front Page and Java is included. I have 4 drop down boxes which work in sequence. select an item in the first, it then asks you to select in the second box, then 3rd then in the final 4th box. This was set up using arrays. My question is how can i put a hyperlink to the items in the last drop down box? I want the last selection to go to a URL. can you tell me what code i need to use and where to insert it? I assume it has to go into the array somewhere. Thanks, Tom

    selection to go to a URL. can you tell me what code
    i need to use and where to insert it? Not without you clarifying your question and showing the relevant bits of your code, and possibly not even then.
    When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
    I assume it
    has to go into the array somewhere. I assume it doesn't, because code doesn't go into arrays.

  • Using ASCII in java

    How can i use ascii in java programming. For example i want convert binary to decimal and use operator such XOR etc to campare to another decimal number. After that convert into ascii code.
    thank you

    If you have a string, then you can convert it into an array of char. Chars are just numbers. (They're numbers that represent unicode characters, but they're still numbers.)
    And all the primitive types in java are essentially binary; you don't have to convert anything to binary unless you mean to convert it for display purposes.
    If you have a string and want to convert it to ascii, then you can specify the encoding type (ascii) while converting to bytes or writing output to a file, etc.
    Hope this helps.

Maybe you are looking for

  • Location of iPhone sync data files or How to not have to re-install all my iPhone apps?

    Hi Folks, I recently did a clean install of Lion on my MacBook Pro and I've chosen to not use Migration Assistant because I don't want to move over a bunch of cruft under my 4+ year old home directory (Tiger > Leopard > SL).  I've been very selective

  • RFC Server - Can't get to work

    I will prefice this by saying I am an ABAP developer with very little VB.Net experience.  Basically I am trying to write an application that will be called from SAP, perform a routine and return some values back to SAP.  In order to prepare for this

  • Itunes wont download to my windows 7 laptop

    i accidently deleted my itunes from my laptop and now that im trying to download the new 10.6 version of itunes it wont work this is what happens when i try to let the download run a pop up shows and says the publisher could not be verified.... so i

  • Option to convert to Pdf missing

    Computer: Win 7 64bit  Adobe XI standard Problem: Using word 2007 select open a file. From the list of file to open, there is no option when I right click to convert to a pdf. I do have this option if I right click a file on my desktop or go through

  • Firefox processes, renders and loads pages slowly.

    Firefox v.29.0.1 loads webpages slowly. When I visit a website it loads information for that page very slowly. (ex. msn.com, irs.gov) There is a small box in the lower left corner stating that it is waiting for----. Then it begins transferring data n