About array cast.

dear all
could someone tell me what's wrong with the following codes?
Object objarr[]
= {new Integer(1), new Integer(2)};
Integer[] intarr = (Integer [])objarr;
it throws out a java.lang.ClassCastException when i ran it. but doesn't the objarr actually represents a Integer array?
regards
Yang Liu

In Java, all objects are by default of Object type. That means an Integer object is of Object type. Similarly a String object is of Object type.
But if I give you an object of type Object, can u absolutely say whether it is an Integer or a String (ofcourse assuming u don't use relection etc) ? No you cannot..
Simlarly when you have a Object array, you can put anything into that array, a String or an Integer etc. So u cannot be sure that an Object array always contains only Integer... That is y u get the class cast exception.....
Ofcourse, this is just the inheritance concept... A BMW is a type of car.. but a car needn't be a type of BMW... it could be a Toyota instead or someting else...
Integer[] intarr = {new Integer(1), new Integer(2)};
Object[] objarr = (Object[]) intarr;
the above code works well.. since all Integer (s) are of Object type in Java....
Hope this helps

Similar Messages

  • Array Casting in java

    Hi,
    I am new to java.Last day Can I cast an arrays in java?For example casting an Object array to a String array or an integer array to a long one.If yes, then what are the rules and restrictions for casting arrays.I tried to google it, but I could not find any useful material.Could any one give me some links where I can get some useful material,books,mock tests etc. regarding preparation for SCJP 1.6?.Please help.
    Thanks in advance

    This is the Berkeley DB, Java Edition forum, and you should post only post questions about that product here. I think you may be looking for basic Java language information, and there are many other websites that can give you that information.

  • A few questions about Arrays and Array Methods.

    I have 2 dimentional arrays in a number of classes, and I wish to pass them about as variables, however, I can only seem to send int[], rather than int[][]. Gives me some compile errors.
    Another thing. How do i get the length of an array?
    I've tried: getLength(object), but it's a 2d array (int[][]), and It's having none of it. How do i get the length of a particular side?

    An object like int[][] only has a single "length", and that is the length of the first dimension. This object is an array that contains arrays of int, and each of those arrays could have a different length. Your 2D array may happen to be rectangular but that isn't a requirement of Java. So you would have to write your own code to find the lengths of the sides. The first side would be theArray.length, the second side would be theArray[0].length, and like that.

  • A question about arrays (brace yourself this is a long post)

    I am working on an assignment that is about generating a random rabbit race by using arrays:
    Rabbit Race
    Write a program to simulate a race between 4 rabbits (numbered 0 to 3). Initially, all contestants are at the start of the race track (position 0) and must race on a 20 meter track (positions numbered 0 to 19). Each participant has its own technique; some run fast, but are sometimes lazy; while others run slowly but steadily. All rabbits make 1 movement one after the other and the one who arrives at the end of the track before the others, wins the race. Here are the rabbit?s strategies :
    At each turn, rabbit 0:
    - sleeps (so does not run), 50% of the time;
    - runs 4 meters, 30% of the time;
    - runs 3 meters, 20% of the time.
    At every turn, rabbit 1 runs 2 meters.
    At each turn, rabbit 2:
    - sleeps, 30% of the time;
    - runs 3 meters, 70% of the time.
    At each turn, rabbit 3:
    - runs 1 meter, 80% of the time;
    - runs 10 meters, 20% of the time.
    The difficulty in the race is that the track has little slippery hills. So after each movement, rabbits can slide down a hill bringing them either closer to the finishing line, or closer to the starting line. How much they slide and in what direction depends on the slope of the hill at their current position, and how many meters they ran during this turn. Each position (or meter) of the hill has a slope represented by an integer between -3 and +2. If the slope is :
    - zero : then, there is no hill at this position and rabbits that reach this position stay there.
    - a negative integer : then, there is a declining side of a hill at this position, and all rabbits reaching this position will slide down
    to a new position that is closer to the finishing line. The new position will be the current position minus the slope times the number of meters the rabbit ran.
    For example, assume a rabbit was in position 10, then ran 5 meters to position 15. If the slope at position 15 is -2, then the new position of the rabbit will be 15 - (-2 x 5) = 25.
    - a positive integer : then, there is a rising side of hill at that position, and all rabbits reaching this position will slide down to a new position that is closer to the starting line. The new position will be the current position minus the slope times the number of meters the rabbit ran.
    For example, assume a rabbit was in position 10, then ran 5 meters to position 15. If the slope at position 15 is +1, then the new position of the rabbit will be 15 - (+1 x 5) = 10.
    Notes on the race:
    - Rabbits have 40 turns to reach the finish line. If after 40 turns no one has managed to reach position 19 (or beyond), then the race is cancelled and no winner is declared.
    - A rabbit?s position can never go below 0. If, after calculating a rabbit?s position, you arrive at a negative position (ex. position -3), then consider that it is at position 0.
    - Consider that any position outside the track (ex. position 0 or position 20) has a slope of 0.
    - If a rabbit reaches position 19 (or goes beyond it), it does not immediately win the race. If any other rabbit reaches position 19 (or beyond) during the same turn, then there is a tie.
    - If at the same turn, one rabbit reaches position 19, and another reaches a position higher than 19, the second rabbit does not win the race because it went further than the first. They both win.
    Ok I know this is long and boring to read but I already completed the majority of the assignment here is my code:
    public class Assignment_3 {
        public static void main (String args[])
             int[] position = new int[20];
             int[] slope = new int[20];
             int[] moveRabbit = new int[4];
                   moveRabbit[1] = 2;
             int[] currentPosition = new int[4];
             int currentPositionandSlope = 0;
             for (int i=0;i<position.length;i++)
             {     position=i;
              System.out.print(position[i] + " ");
         System.out.println();
         for (int i=0;i<(position.length-5);i++)
         {     slope[i]=(int) (-3 + Math.random()*5);
         for (int i=0;i<position.length;i++)
              System.out.print(slope[i] + " ");
         System.out.println();
         for (int turn=1;turn<=40;turn++)
              int randomNb0 = (int) (Math.random () * 100);
    int randomNb2 = (int) (Math.random () * 100);
    int randomNb3 = (int) (Math.random () * 100);
              if (randomNb0<=50)
                   moveRabbit[0] = 0;
              else if (randomNb<=30)
                   moveRabbit[0] = 4;
              else
              moveRabbit[0] = 3;
              if (randomNb2<=30)
                   moveRabbit[2] = 0;
              else
              moveRabbit[2] = 3;
              if (randomNb3<=80)
                   moveRabbit[3] = 1;
                   else
              moveRabbit[3] = 10;
    for (int j=0;j<=3;j++)           
    System.out.println ("Rabbit" + j + " is at position " + position[currentPosition[j]]);
    if (slope[currentPosition[j]+moveRabbit[i]] < 0)
         currentPositionandSlope = position[currentPosition[j]+moveRabbit[j]] - (slope[currentPosition[j]+moveRabbit[j]] * moveRabbit[j]);
    else if (slope[currentPosition[j]+moveRabbit[i]] > 0)
         currentPositionandSlope = position[currentPosition[j]+moveRabbit[j]] - (slope[currentPosition[j]+moveRabbit[j]] * moveRabbit[j]);
    else
         currentPositionandSlope = (currentPosition[j]+moveRabbit[j]);
    System.out.println ("it will move by " + moveRabbit[j] + ", but at position " + (position[currentPosition[j]] + moveRabbit[j]) + " there is a slope of " + slope[currentPosition[j] + moveRabbit[j]]);
    System.out.println ("so it will slip by " + (position[currentPositionandSlope] - moveRabbit[j]) + " positions, and end up at position " + position[currentPositionandSlope]);
    currentPosition[j] += currentPositionandSlope;
    *Ok basically my question is that in the assignment there is an example output where the rabbit is at position 21 but the array is only 20 in length and my program crashes if i go beyond the array length.*
    The example output is here:
    Welcome to the 4 rabbit race:
    position: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
    slopes: 0 0 1 -2 1 0 -1 -1 1 -2 1 0 -1 -1 1 0 0 0 0 0
    TURN #1
    rabbit 0 is at position 0
    it will move by 3, but at position 3 there is a slope of -2
    so it will slip by 6 positions, and end up at position 9
    rabbit 1 is at position 0
    it will move by 2, but at position 2 there is a slope of 1
    so it will slip by -2 positions, and end up at position 0
    rabbit 2 is at position 0
    it will move by 3, but at position 3 there is a slope of -2
    so it will slip by 6 positions, and end up at position 9
    rabbit 3 is at position 0
    it will move by 1, but at position 1 there is a slope of 0
    so it will slip by 0 positions, and end up at position 1
    TURN #2
    rabbit 0 is at position 9
    it will move by 0, but at position 9 there is a slope of -2
    so it will slip by 0 positions, and end up at position 9
    rabbit 1 is at position 0
    it will move by 2, but at position 2 there is a slope of 1
    so it will slip by -2 positions, and end up at position 0
    rabbit 2 is at position 9
    it will move by 3, but at position 12 there is a slope of -1
    so it will slip by 3 positions, and end up at position 15
    rabbit 3 is at position 1
    it will move by 1, but at position 2 there is a slope of 1
    so it will slip by -1 positions, and end up at position 1
    TURN #3
    rabbit 0 is at position 9
    it will move by 3, but at position 12 there is a slope of -1
    so it will slip by 3 positions, and end up at position 15
    rabbit 1 is at position 0
    it will move by 2, but at position 2 there is a slope of 1
    so it will slip by -2 positions, and end up at position 0
    rabbit 2 is at position 15
    it will move by 3, but at position 18 there is a slope of 0
    so it will slip by 0 positions, and end up at position 18
    rabbit 3 is at position 1
    3
    it will move by 10, but at position 11 there is a slope of 0
    so it will slip by 0 positions, and end up at position 11
    TURN #4
    rabbit 0 is at position 15
    it will move by 0, but at position 15 there is a slope of 0
    so it will slip by 0 positions, and end up at position 15
    rabbit 1 is at position 0
    it will move by 2, but at position 2 there is a slope of 1
    so it will slip by -2 positions, and end up at position 0
    *rabbit 2 is at position 18*
    *it will move by 3, but at position 21 there is a slope of 0*
    *so it will slip by 0 positions, and end up at position 21*
    *We have a potential winner...*
    rabbit 3 is at position 11
    it will move by 1, but at position 12 there is a slope of -1
    so it will slip by 1 positions, and end up at position 13
    So yeah :) that's basically my question (all this text for a simple question like that lol)
    If you've managed to get to the end of my post then any guidance on my code would be appreciated too :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I'm not going to read that long post. As suggested, produce an SSCCE
    and paste in the exact, complete error message, and indicate clearly which line causes it.
    I did notice this though:
    Ok basically my question is that in the assignment there is an example output where the rabbit
    is at position 21 but the array is only 20 in length and my program crashes if i go beyond the array length.Either you're misunderstanding something, or the assignment has a typo. If you have an array of length 20, then the indices are 0..19.
    Maybe the instructor is calling index 0 position 1--separating Java's array impelementation details from
    colloquial 1-based counting, so that the rabbit starts at "position 1" (index 0) goes through "position 20"
    (index 19), and when he's done, he's "at postion 21"--i.e., past the finish line, off the end of the course, etc.
    This won't correspond to any index in the array, but can still be considered a logical position in the race. "Oh, he's
    at position 21. He's done. There's nothing more to do with the array, as it has no slot corresponding to
    this 'done' position."
    That's pure speculation on my part. You'll have to ask your instructor or figure out for yourself what's going on.

  • Describe non-generic array cast in JLS3 as being unchecked

    This method :
        static <T, U extends T> U[] cast(T[] a) { return (U[]) a; }will generate the warning: [unchecked] unchecked cast, found: T[], required: U[].
    And it should. Wouldn't it be appropriate if
        static Object[] cast(String[] a) { return (String[]) a; }would produce the same warning?
    If you do that, you could translate the declaration
      T[] at = new T[255]
      String[] as = new String[255]into
    Array<T> at = Array.<T>newInstance(255);
    Array<String> as = Array.<String>newInstance(String.class, 255);where java.lang.reflect.Array would be something like
    package java.lang.reflect.Array;
    public final class Array<T> implements Iterable<T> {
        public final int length;
        private Type memberType;
        private Array(Type memberType, int length) {
            this.memberType = memberType;
            this.length = length;
        public native T getMember(int i);
        public native void setMember(int i, T member);
        public native java.util.Iterator<T> iterator();
       public static <U> Array<U> newInstance(int length) {
           return new Array<U>(null, length);
       public static <U> Array<U> newInstance(Class<U> memberClass, int length) {
           return new Array<U>(memberClass, length);

    Sorry, I created a bad example. It should have been:
        static <T, U extends T> T[] cast(U[] a) { return (T[]) a; }and
        static Object[] cast(String[] a) { return (Object[]) a; }The point is that an array of String is different from an array of Object and casts between them is unsafe. Throwing an ArrayStoreException if the wrong type is assigned is just a workaround for lack generic types in pre-Tiger Java. Now that we will have generics, I think it would be appropriate if Java arrays would be treated as proper generic types. For those that are afraid of breaking backwards compatiblility, the erasure mechanism should be able to take care of that.

  • WHY IS array CASTING NOT WORKING ?

    data object:
    class myData extends BaseData
    class x
    BaseData[] lData = null;
    setData(BaseData[] aData)
         lData = aData;          
    getData(BaseData[] aData)
    return lData;     
    class y
    myData[] a = new myData[];
    x xx = new x();      
    xx.setData(a);
    xx = (myData[])xx.getData(); <---casting doesnt work !!               
    }

    well IData IS an array so that's not the problem
    The problem is that an array is an object with its own inheritance but it has no knowledge of the inheritance of the objects it contains. So String[] does not extends Object[] even though String extends Object. But all 4 extends Object :)
    run this little to see to what interfaces/classes you can cast your arrays:
    public class Test {
         public static void main(String[] args) {
              Class cl = args.getClass();
              Class[] interfaces = cl.getInterfaces();
              System.out.println( "classes and super-classes" );
              while (cl != null) {
                   System.out.println( "    "+cl );
                   cl = cl.getSuperclass();
              System.out.println( "interfaces" );
              for (int i = interfaces.length; i-->0; )
                   System.out.println( "    "+interfaces[i] );
    }

  • How could I retrieve metadata about Array Type and Table Type?

    I use DatabaseMetaData.getUDTs() method for obtain metadata about Object Types, but this method doesn't work with Array Type and Table Type.

    JJ,
    Go into the diagrams of the DBTools List Columns and DBTools Get Properties respectively. When you inspect this diagram, you will see the raw ActiveX properties and methods called to get the size information. The value of -1 means the requested recordset is already closed. This is the sort of thing that is controled by the driver (ODBC, OLE DB, Jet, etc) you are using. Notice that you can right click on the property and invoke nodes and get more information about these specific items directly from the ADO online help.
    Crystal

  • Problem about type casting

    Hello friends. I m getting some problem related to casting. I m working on web service testing software where my test tool file generates the contents of the web service which i entered runtime. iI can use java.lang.reflect . How do v get the class name of array? So that i can use the Classname.getDeclaredMethods();.
    Please give me suggetion.

    Maybe you are having problems because getDeclaredMethods() returns an empty array for array classes?import java.lang.reflect.Method;
    public class ArrayMethods {
         static void dumpMethods(Class c) {
              System.out.println();
              Method[] ma;
              do {
                   System.out.println(c.toString());
                   ma = c.getDeclaredMethods();
                   for(int i=0;i<ma.length;++i) {
                        System.out.println(ma.toString());
                   c = c.getSuperclass();
              } while (ma.length==0);
         public static void main(String[] arg) throws Exception {
              dumpMethods(Integer.class);
              dumpMethods(int[].class);
              dumpMethods(Class.forName("[I"));
              dumpMethods(Class.forName("[[I"));
              dumpMethods(Class.forName("[Ljava.lang.Object;"));

  • Array Cast Question Puzzling me

    The question below puzzles me. The answer states that the result is a class cast exception because o1 is an int [] [] not a int []
    But I thought the point of line 7 is to say "I know it is a 2D array but I want to cast it to a 1D array - I know I am losing precision here".
    Given:
    1. class Dims {
    2. public static void main(String[] args) {
    3. int[][] a = {{1,2,}, {3,4}};
    4. int[] b = (int[]) a[1];
    5. Object o1 = a;
    6. int[][] a2 = (int[][]) o1;
    7. int[] b2 = (int[]) o1;
    8. System.out.println(b[1]);
    9. } }
    What is the result?
    A. 2
    B. 4
    C. An exception is thrown at runtime
    D. Compilation fails due to an error on line 4.
    E. Compilation fails due to an error on line 5.
    F. Compilation fails due to an error on line 6.
    G. Compilation fails due to an error on line 7.
    Answer:
    3 C is correct. A ClassCastException is thrown at line 7 because o1 refers to an int[][]
    not an int[]. If line 7 was removed, the output would be 4.
    &#730; A, B, D, E, F, and G are incorrect based on the above. (Objective 1.3)

    While you could approximate casting a 2D array to a 1D array in C/C++ by just grabbing a pointer to your first array and then overrunning array bounds (relying on how C/C++ allocates 2D arrays and the lack of bounds checking), Java's strong typing and bounds checking makes this impossible.
    If you want to do something similar in Java, you will need to create a new 1D array of the proper size and copy the elements stored in your 2D array into this new array. That being said, a database is almost guaranteed to be a better solution.

  • Details about arrays

    i what details about simple array function.. how to declare array function

    google google google google
    are there really this many people who don't know about google?
    www.google.com
    -Type in "java arrays"
    -Hit enter
    -Click on the first result
    -Learn

  • Array casting: ClassCastException

    import java.util.Vector;
    public class X
    public static void main(String args[])
         //first part
    String [] array = {"1","2", "3"};
    Object [] objs = array;
    array = (String[])objs;
    for( int i =0 ; i < array.length; i++)
    System.out.println(array);
         //second part
    Vector v = new Vector();
    v.add("1");
    v.add("2");
    v.add("3");
    objs = v.toArray();
    array = (String[])objs;
    for( int i =0 ; i < array.length; i++)
    System.out.println(array[i]);
    Why does the first part work properly but the second cause ClassCastException? Even if an array was instantiated as Object[] in toArray method casting MUST be ok. I work with an instances in array but not with array. An array only contains an objects I work with. It's only technical structure! Why does it cause ClassCastException?

    >
    Yes. I know it. The point is WHY it was done in this
    way? What can I do with the type of array? NONE. The
    actual information is CONTAINED in array. So array
    is only technical structure. I can't derive it, it has
    no virtual mechanisms. The actual objects I need are
    stored in array. The type of them is important. It
    looks like miss of language structure.
    The basic question here is a fundamental part of polymorphism - you cannot cast an Object into one that it is not.
    Object a = new Object();
    String b = (String) a;That code will also compile, but it is just as incorrect as your code. The problem is that "a" will never be a String. There may be ways to convert it into a String, but the object a will always be of type "Object" and never extend String, so it cannot be cast.
    Similarly, an array of type Object[] will always be of type Object[]. It cannot be cast to String[], because it will never have String[] as a superclass, if you will. The rules for working with arrays are exactly the same as working with the object which is the base type of the array.
    In order to be able to do a cast from Object[] to String[], there would have to be a runtime check which would ensure that every element in the Object[] was, in fact, a String. But the cast check in the compiler is just looking up the extends and implements chains. If you want to implement a runtime cast, Java basically leaves that up to you.
    And as has been mentioned, they do let you provide the array to be used as well.

  • About array in applet

    hi all..
    i want to initialize an fixed-size array in applet
    and i write this
    byte[] array=new byte[40];
    but now what is the type of the number "40"?
    is short? or byte? or int??
    i'm confused about this,
    or i should write byte[] array=new byte[(short) 40];
    or byte[] array=new byte[(byte) 0x28]; ??
    thanx for replies

    it can't be an int unless the vendor is supporting it. Chances are to support int would cost a lot more therefore you don't see it often. So your "40" would be a short. If you want to use it as a 0x28 the results are the same.
    One gotcha about the JC implementation is to be careful when performing calculations. Theycould by default, get interpreted at an int by the J2SE JDK compiler.
    for example, offset = (apduBuffer[ISO7816.OFFSET_P1]&0xFF) * dataMax ;
    might not work !
    correct it to read: offset = ( short ) ( (apduBuffer[ISO7816.OFFSET_P1]&0xFF) * ( short )240 );
    You only find this out when you create your cap file by NOT utilizing int.

  • Hello and a question about Arrays

    Hello! I am a student working towards a CIS degree, I'm only in my second term, so I have a long way to go still. Next term (starts in November) I'll be starting my first language (Java) so I figured this is a good spot to register and get acquainted with all of you.
    Anyway, right now I'm in a programming logic and design class. In this class we use Pseudocode to get the basic constructs of programming down without doing anything language specific. I just read the chapter that introduces Arrays and had a difficult time following it. Could any of you take a minute and give me your definition of what exactly an array is and how it works? Or maybe point me to a link that might help me? I've got the 'jist' of it, but the book jumps right into algorithms using arrays without much explaination as to what they are.
    Thanks for any response and for helping a programming "n00b".
    -Rawhide

    >
    Hello! I am a student working towards a CIS
    CIS degree, I'm only in my second term, so I have a
    long way to go still. Next term (starts in November)
    I'll be starting my first language (Java) so I
    figured this is a good spot to register and get
    acquainted with all of you.
    Anyway, right now I'm in a programming logic andThink of an array as a series of boxes. These boxes store data for three
    elements. So you would have three boxes that store one element of data.
    So 'this' array has a capacity of three. If you want something bigger,
    you'd create a array with more boxes, say 10. Then your array has a capacity of 10.
    To get to anything from a array, you either need to :
    a) go through all the elements of the array
    b) or actually know the element you want to retrieve.
    The second case is simple enough, you usually just specify the element you want. For example the first element would be zero.(counting starts from zero). The last element would be 9 (10 -1).
    The first case requires some knowledge of looping, you'd generally itterate from the first until the last element of the array, in each and every element that you are at, do the stuff you need to do. This will go on until the end of the array is reached.
    for(int i=0; i<=arraylength;i++ ) {
    do some stuff. like print out to the console.
    I'm not giving you any specific java code because you didn't ask for any and you were doing a course that wasn't language specific. So I figured that may be a simpler explanation(was it?) was in order.
    Let me know if you need clarification.
    and design class. In this class we use Pseudocode to
    get the basic constructs of programming down without
    doing anything language specific. I just read the
    chapter that introduces Arrays and had a difficult
    time following it. Could any of you take a minute
    and give me your definition of what exactly an array
    is and how it works? Or maybe point me to a link that
    might help me? I've got the 'jist' of it, but the
    book jumps right into algorithms using arrays without
    much explaination as to what they are.
    Thanks for any response and for helping a programming
    "n00b".
    -Rawhide

  • Question about arrays

    I have a question regarding arrays. I have a contact class and two classes that extend from it a SchoolContact class and FamilyContact class. Right now as my code is I have three diffrernt arrays to hold all the info. Is there a way to store all this info into one array and print out only the School contacts at one time if the user enters that option or print out all the options at one time if the user selects that? my code is below
    //The imports below are for I/O
    import java.util.*;
    import java.io.*;
    // Declare a public class
    public class CodeExample {
         public static void main(String[] args) {
              // Create scanner
              Scanner sc = new Scanner(System.in);
              //Declare array to hold school contact
              SchoolContact[] schoolContactInfo = new SchoolContact[10];
              FamilyContact[] familyContactInfo = new FamilyContact[10];
              Contact [] contactInfo = new Contact [10];
              // Declare variables
              int menuOption, creditHours, area, prefix, suffix, studentId, studentContactsSoFar = 0, familyContactsSoFar = 0, contactsSoFar = 0;
              double gpa;
              char studentData, familyRelationOption;
              String menuOption2, menuOption3;
              // Get menu to display
              do {
                   System.out.println("-----MENU-----");
                   System.out.println("1) Enter a Student Contact");
                   System.out.println("2) Enter a Family Contact");
                   System.out.println("3) Enter a Contact");
                   System.out.println("4) Display Student Contacts");
                   System.out.println("5) Display Family Contacts");
                   System.out.println("6) Display Contacts");
                   System.out.println("7) Display All Contacts");
                   System.out.println("8) Quit");
                   System.out.println("Selection:");
                   menuOption = sc.nextInt();
                   SchoolContact schoolContact = new SchoolContact();
                   FamilyContact familyContact = new FamilyContact();
                   Contact contact = new Contact();
                   // Implement switch statement to
                   switch (menuOption) {
                   // If user enters 1 to create contact this will be displayed to user
                   case 1:
                        System.out.println("Enter The First Name of The Student");
                        schoolContact.setFirstName(sc.next());     
                        System.out.println("Enter The Last Name of The Student");
                        schoolContact.setLastName(sc.next());
                        System.out.println("Enter the Student ID of this person: 900");
                        schoolContact.setStudentId(Integer.parseInt("900" + sc.next()));
                        System.out.println("G)Enter The GPA For This Student");
                        System.out.println("H)Enter The Number Of Completed Credit Hours");
                        menuOption2 = sc.next().toUpperCase();
                        studentData = menuOption2.charAt(0);
                        // Prompts the user for the next choice
                        if (studentData == 'G') {
                             System.out.println("GPA: ");
                             gpa = sc.nextDouble();
                             //create the Data object
                             Data data = new Data();
                             data.setStudentGPA(gpa);
                             //add it to the contact
                             schoolContact.setData(data);
                             else if (studentData == 'H') {
                                  System.out.println("Hours: ");
                                  creditHours = sc.nextInt();
                                  //create the Data object
                                  Data data = new Data();
                                  data.setStudentCreditHours(creditHours);
                                  //add it to the schoolcontact
                                  schoolContact.setData(data);
                                  else {
                                       System.out.println("Invalid Entry");
                        System.out.println("Enter The Phone Number of This Student");
                        System.out.println("(###)-###-####: ");
                        area = sc.nextInt();
                        prefix = sc.nextInt();
                        suffix = sc.nextInt();
                        //create the phone object
                        Phone_Number studentPhone = new Phone_Number(area, prefix,     suffix);
                        //add it to the Schoolcontact
                        schoolContact.setPhone(studentPhone);
                        //store info in an array
                        schoolContactInfo[ studentContactsSoFar ] = schoolContact;
                        //increase the counter to point to the next free location (if any)
                        studentContactsSoFar++;
                        break;
                   case 2:
                        System.out.println("Enter the First Name of The Contact");
                        familyContact.setFirstName(sc.next());     
                        System.out.println("Enter The Last Name of The Student");
                        familyContact.setLastName(sc.next());
                        System.out.println("Enter The Relationship of This Contact");
                        System.out.println("A) SISTER");
                        System.out.println("B) BROTHER");
                        System.out.println("C) MOTHER");
                        System.out.println("D) FATHER");
                        System.out.println("E) OTHER");
                        menuOption3 = sc.next();
                        familyRelationOption = menuOption3.charAt(0);
                        if (familyRelationOption == 'A') {
                             System.out.println("Relationship: SISTER ");
                             familyContact.setRelationType(FamilyContact.RelationType.SISTER);
                             else if (familyRelationOption == 'B') {
                             System.out.println("Relationship: BROTHER ");
                             familyContact.setRelationType(FamilyContact.RelationType.BROTHER);
                                  else if (familyRelationOption == 'C') {
                                       System.out.println("Relationship: MOTHER ");
                                       familyContact.setRelationType(FamilyContact.RelationType.MOTHER);
                                       else if (familyRelationOption == 'D') {
                                            System.out.println("Relationship: FATHER ");
                                            familyContact.setRelationType(FamilyContact.RelationType.FATHER);
                                            else if (familyRelationOption == 'E') {
                                                 System.out.println("Relationship: OTHER ");
                                                 familyContact.setRelationType(FamilyContact.RelationType.OTHER);
                        System.out.println("Enter The Phone Number of This Contact");
                        System.out.println("(###)-###-####: ");
                        area = sc.nextInt();
                        prefix = sc.nextInt();
                        suffix = sc.nextInt();
                        //create the phone object
                        Phone_Number familyContactNumber = new Phone_Number(area, prefix,     suffix);
                        //add it to the familyContact
                        familyContact.setPhone(familyContactNumber);
                        //store info in an array
                        familyContactInfo[ familyContactsSoFar ] = familyContact;
                        //increase the counter to point to the next free location (if any)
                        familyContactsSoFar++;
                        break;
                   case 3:
                        System.out.println("Enter The First Name of The Contact");
                        contact.setFirstName(sc.next());     
                        System.out.println("Enter The Last Name of The Contact");
                        contact.setLastName(sc.next());
                        System.out.println("Enter The Phone Number of This Contact");
                        System.out.println("(###)-###-####: ");
                        area = sc.nextInt();
                        prefix = sc.nextInt();
                        suffix = sc.nextInt();
                        //create the phone object
                        Phone_Number contactNumber = new Phone_Number(area, prefix,     suffix);
                        //add it to the contact
                        contact.setPhone(contactNumber);
                        //store info in an array
                        contactInfo[ contactsSoFar ] = contact;
                        //increase the counter to point to the next free location (if any)
                        contactsSoFar++;
                        break;
                   case 4:
                        System.out.println("-----Student Contacts-----");
                        //print each stored contact
                        for( int i = 0 ; i < studentContactsSoFar ; i++ )
                             System.out.println( (i+1) + ". " + schoolContactInfo.toString() + "\n");
                        break;
                   case 5:
                        System.out.println("-----Family Contacts-----");
                        //prints each stored contact
                        for( int i = 0 ; i < familyContactsSoFar ; i++ )
                             System.out.println( (i+1) + ". " + familyContactInfo[i].toString() + "\n");
                        break;
                   case 6:
                        System.out.println("-----Contacts-----");
                        //prints each stored contact
                        for( int i = 0 ; i < contactsSoFar ; i++ )
                             System.out.println( (i+1) + ". " + contactInfo[i].toString() + "\n");
                        break;
                   case 7:
                        System.out.println("Calling Case 7");
                        for( int i = 0 ; i < contactsSoFar ; i++ )
                             System.out.println( (i+1) + ". " + contactInfo[i].toString() + "\n");
                        break;
                   case 8:
                        System.out.println("Program Ended");
                        break;
              } while (menuOption != 8);

    how would I go in printing the contacts from one array, then the next array and so on?
    case 7:
        System.out.println("Calling Case 7");
        for( int i = 0 ; i < studentContactsSoFar ; i++ ) {
            System.out.println( (i+1) + ". " + schoolContactInfo.toString() + "\n");
    for( int i = 0 ; i < familyContactsSoFar ; i++ ) {
    System.out.println( (i+1) + ". " + familyContactInfo[i].toString() + "\n");
    for( int i = 0 ; i < contactsSoFar ; i++ ) {
    System.out.println( (i+1) + ". " + contactInfo[i].toString() + "\n");
    break;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Question about array append

    Hi,
    I have a for loop and an array outside the for loop. In each iteration some values are sent to the array.
    For example, after first loop, I send following data to array:
    2 3 4 5
    4 5 6 7
    after the second loop, other data send to array again and will overwrite the former data in array. How can I append the data to the array?
    I try to use "Insert into array.vi", but how to keep the former array's data?
    Thanks.

    You have quite a few options.
    The attached VI (LabVIEW 7.1) shows two possibilities, either building the table (2D string) or building the array (2D DBL).
    (NOTES: If this is in a fast FOR loop it is not useful to update the display inside the loop, simply place the output terminals outside the FOR loop, connected to the shift registers on the right. If you know the final array size and it is relatively big, it is more efficient to initialize the shift register with the full sized array (e.g. filled with zeroes or NaNs), then replace array sections as you go in the loop. This avoids array resizing operations.)
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    temp_ni_MOD.vi ‏43 KB

Maybe you are looking for