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;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

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

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

  • Hi, i got some question about arrays.

    My question is how do i auto increase the array size for theList[0] to store the over time if the user enter more than 1 employee.
    static void showPayInfo(int num1 , int num2)
              for(int coloum = 1 ; coloum <= num2 ; coloum++)
                   System.out.print("Enter employee's over time  $: ");
                   ot = CspInput.readDouble();
                   Double = ot;
                   getDouble(Double);
    static double ot , Double;
         static void getDouble(double Double)
              double[] theList = new double[2];
              theList[0] = ot;
         public static void main(String[] args)
              int a;
              System.out.print("How many employees : " );
              a = CspInput.readInt();
              showPayInfo(1,a);
         }

    how to create the list?
    import java.util.ArrayList;
    class testArrayList {
       public static void main(String[] args) {
         ArrayList<String> list1 = new ArrayList<String>();
         // Populate list
         for (int i = 0; i < 5; i++) {
           list1.add("List item " + i);
         // Show list
         for (int i = 0; i < list1.size(); i++) {
           System.out.println(list1.get(i));
    }

  • Hopefully an easy question about arrays

    hi there
    is there any way of creating an array of objects that is of unspecified size at the time of creating and then add objects as and when they are read from a file?
    longer explanation:
    i am creating molecule visualization software. the molecule's structure is stored in a text file, ie each line has info on one atom ie 3d coords etc. i'm storing the molecule structure in an object (Molecule.java) which has an array (Structure[]) of atoms (Atom.java). obviously molecules can have any number of atoms in it and you don't know how many until you've gone through the whole file and counted. The only way i can think of doing it is to go through the whole file, coun the atoms, close the file, create the Molecule object with the structure array size of NoOfAtoms and then open the file again and add the atoms as i go through them again. however, i refuse to believe this is the most efficient way of doing it as i have to go throguh the same file twice which brings me back to my original question.
    as i said i'm hopeing there is a simple answer
    cheers

    Use a Collection . Use a Vector, ArrayList or even a Hashtable. You do not need to define the size of these objects and can add and remove Objects from them whenever you want

  • A question about arrays. Please Help

    Ok here is my question lets say i have a multie varible array such as
    int[][] thisList = new int[3][64];And I have a number of other arrays that are single variable arrays, and which have data stored in them.
    List1[64]
    List2[64]
    List3[64]is there a way i can store all these three list in the multie varible array?
    for example i know i can do this, > Correct me if i am wrong
    List1 = List2; where List1 one now contains all the elements that List2 has.
    but is there a way i can
    us the same format with a multie varible array, to store all three list in it.
    such as thisList[1][] = List1; thisList[2][] = List2[]; Thanks

    for example i know i can do this, > Correct me if i
    am wrong
    List1 = List2; where List1 one now
    contains all the elements that List2 has.There will be one array. Both the List1 and List2 reference variables will point to that same array.
    (By the way, convention in Java is for variables to start with lowercase.)
    >
    but is there a way i can
    us the same format with a multie varible array, to
    store all three list in it.
    such as thisList[1][] = List1; thisList[2][] =
    List2[];
    You can do thisList[1] = List1 if thisList is an int[][] and List1 is an int[]. However, that will not copy any ints. It will just do the same as the above--cause the reference thisList[1] to point to the same array object as List1 does.
    If you want to copy values from one array to another, use System.arraycopy.

  • Very simple and quick question about Arrays

    Hi,
    I have the following code to produce a student grades provessing system. I have got it to store data in the array, i just cant figure out how to add the integers from the row to produce a total. Thats all I want to do create a total from the 6 marks and add a percentage.
    Any help would be greatly appreciated.
    -------------CODE BELOW----------------------
    import java.util.*;
    public class newstudent1_2
    public static void main (String[]args)
    System.out.println ("-----------------------------------------------"); //Decorative border to make the welcome message stand out
    System.out.println (" Welcome to Student Exam Mark Software 1.2"); //Simple welcome message
    System.out.println ("-----------------------------------------------");
    int [][] mark;
    int total_mark;
    int num_students;
    int num_questions = 9;
    Scanner kybd = new Scanner(System.in);
    System.out.println("How many students?");
    num_students =kybd.nextInt();
    mark = new int[num_students][num_questions] ;
    for (int i=0; i<num_students; i++)
    System.out.println("Enter the Students ID");
    String student_id;
    student_id =kybd.next();
    System.out.println("Student "+i);
    for( int j=1; j<num_questions; j++)
    System.out.println("Please enter a mark for question "+j);
    mark[i][j]=kybd.nextInt();
    System.out.print("id mark1 mark2 mark3 mark4 mark5 mark6 mark7 mark8");
    //This section prints the array data into a table
    System.out.println();
    for (int i=0; i<num_students; i++)
    for( int j=0; j<num_questions; j++)
    System.out.print(mark[i][j]+"\t"); //the \t is used to add spaces inbetween the output table
    System.out.println();
    --------------END OF CODE---------------
    Thanks.

    I had to do this same sort of thing for a school assignment but i didnt use an array.
    import java.text.DecimalFormat;
    import TurtleGraphics.KeyboardReader;
    public class grade_avg
         public static void main(String[] args)
              int grade, total = 0, count = 0;
              double avg = 0.0;
              KeyboardReader reader = new KeyboardReader();
              DecimalFormat df = new DecimalFormat("0.00");
         for (;;)
                   grade = reader.readInt("Please enter a grade: ");
              if (grade > 0)
                        total = total + grade;
                        count ++;
              if (grade == 0)
                        avg = total / count;
                        System.out.println("The average is: " + df.format(avg));
                        System.exit(0);
    }output looks like:
    Please enter a grade: 100
    Please enter a grade: 50
    Please enter a grade: 0
    The average is: 75.00

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

  • Simple newbie question about arrays..

    Hello all,
    I have two arrays declared like so below the class header:
    String Players[];
    String Final[];
    I have a method like the following:
    public String[] CollectPlayers() {
    Players[0] = new String(txtPlayer1.getString());
    return Players;
    I am calling this method like so
    Final = CollectPlayers();
    Basically not working, giving nullpointerexception, but I feel that I am fundamentally not understanding something, so here is what I want...
    A method that returns an array and (ideally) use this method directly in creating a ChoiceGroup, like this...
    optBull = new ChoiceGroup("Bully", ChoiceGroup.EXCLUSIVE, CollectPlayers(), arrImage);
    Is this possible? Any ideas?
    Thanks in advance
    poncenby

    A few points:
    - You almost never need to call new String(String).
    - You may want to create an ArrayList (dynamic array) and then call toArray(new Players[0]) if you need it to be a fixed array.
    e.g.
    final List players = new ArrayList();
    public List collectPlayers(List players) {
        List finals = new ArrayList();
        for(int i=0;i<players.size();i++) {
            Player player = (Player) players.get(i);
            finals.add(players.getResult());
        return finals;
    players.add(new Player("anne"));
    players.add(new Player("bob"));
    players.add(new Player("fred"));
    List finals = collectPlayers(players);

  • Question about array!

    Is there any way to make external array, which could be used by more than one application or flash movie?

    The simplest solution is often the best.
    If you are only using arrays: use a text file.
    Text files can be read into any application and you can use the [split] method with a delimiter to create an array
    If you are using both arrays and objects: use JSON
    JSON can handle primitive objects which can also be used in any environment beyond Flash
    Both solutions involve creating a text file of some sorts.  Load the text file with a URLLoader (flash) or as binary (any other) and parse the text as an array or JSON.
    Why you dont want to add an 'External Array' to an SWF
    In all situations you should consider maintainance and updating.  If you create the array in an SWF file, all changes to the array (large or small) will involve you having to re-complie and re-upload the new SWF file.  This will get VERY time consuming the larger the project scale.  Using a text file is a lot less foot print on processing and file size.

  • Question about the programming of a legend

    Hello everybody,
    I have a question about the programming of a waveform's legend. I
    already asked here in this forum about the legend programming (03)
    months ago.
    I went satisfied but I ve just noticed that this code
    (See Code old_legend_test.llb with main.vi as main function) operates a
    little different from my expectances.
    Therefore I have a new question and I want to know if it
    is possible by labview programming to plot and show, on a waveform
    chart, a signal with activ plot superior to zero (0) without to be
    obliged to plot and show a signal with activ plot equal to zero (0) or
    inferior to the desired activ plot.
    I give you an example
    of what I m meaning. I have by example 4 signals (Signal 0, 1, 2 and 3)
    and each signal corresponds respectively to a channel (Chan1, Chan2,
    Chan3, Chan4). I want to control the legend (activ plot, plot name and
    plot color) programmatically. Is it possible with labview to plot signal
    1 or 2 or 3 or (1, 3) or (2,3) or (1,2,3) or other possible combination
    without to active the signal with the corresponding activ plot zero
    (0)?
    Let see the labview attached data
    (new_legend_test.llb with main.vi as main function). When I try to
    control the input selected values again I get them back but I don't
    understand why they have no effect on the legend of my waveform chart.
    Could somebody explain me what I m doing wrong or show me how to get a
    correct legend with desired plots? Thank by advance for your assistance.
    N.B.
    The
    both attached data are saved with labview 2009.
    Sincerly,PrinceJack
    Attachments:
    old_legend_test.llb ‏65 KB
    new_legend_test.llb ‏65 KB

    Hi
    princejack,
    Thanks for
    posting on National Instruments forum.
    The behavior
    you have is completely normal. You can control the number of row displayed in
    the legend and this rows are linked to the data you send to your graph. Thus,
    if you have 3 arrays of data, let say chan1, chan2 and chan3, you can choose
    which data you want to display in your graph using the property node (Active
    plot and visible). But for the legend as you send 3 plots there is an array of
    the plot name [chan1, chan2, chan3] and you can display 0, 1, 2 or 3 rows of
    this array but you cannot control the order in this array! So, to be able to
    change this array you have to only send data you need to you graph. I'm not
    sure my explanations are clear so I have implemented a simple example doing
    that.
    Benjamin R.
    R&D Software Development Manager
    http://www.fluigent.com/
    Attachments:
    GraphLegend.vi ‏85 KB

  • Question about IDashedAttributeValues interface

    Hi to everyone,<br />I have a question about IDashedAttributeValues interface.<br />If I would like to apply custom dashes kDashedAttributeValuesBoss to a page item. I would expect that my code will look like this:<br /><br />InterfacePtr<IDashedAttributeValues> pAttribute(::CreateObject(kDashedAttributeValuesBoss));<br /><br />pAttribute->SetPhase( nPhase );<br />pAttribute->SetCornerAdjustment((IDashedAttributeValues::CornerAdjustment)nCornerAdjust ment);<br />pAttribute->SetValue( 0, nDash0 );<br /><br />But InDesign crashes at SetValue code. I could understand InDesign. It is out of range. But, how to specify the length of value array or to add value into array?<br /><br />Thanks in advance,<br />Alexander Staroverov<br />Developer Engineer<br />Comosoft GmbH

    Thank you to all, I have found the answer in SDK samples:<br /><br />void SnpGraphicHelper::AddDashedValues(const K2Vector<PMReal>& dashAndGapValues)<br />{<br />IDataBase* db = fItemList.GetDataBase();<br />InterfacePtr<IDocument> theDocument(db, db->GetRootUID(), UseDefaultIID());<br />     InterfacePtr<IUIDData> uidData(::CreateObject2<IUIDData>(kDashedAttributeValuesBoss));<br />     ASSERT(uidData != nil);<br />     uidData->Set(::GetUIDRef(theDocument));<br />     InterfacePtr<IDashedAttributeValues> dashedAttributeValues(uidData, UseDefaultIID());<br />     if (dashedAttributeValues != nil && dashAndGapValues.size() > 0) {<br />          for (int32 i = 0; i < dashAndGapValues.size(); i++) {<br />               dashedAttributeValues->SetValue(i, dashAndGapValues[i]);<br />          }<br />          this->AddAnAttribute(dashedAttributeValues);<br />     }<br />}

  • Question about get web service result in actionscript and convert data format

    Hi, All
    I have question about how to get dataset from web services
    and put it in tree structure. I have 2 questions about this:
    1, How can I get data correctly in actionscript?
    I have no problem to get data by
    <mx:ArrayCollection id="acFolder"
    source="{mx.utils.ArrayUtil.toArray(MyGServices.getFolder.lastResult)}"
    />
    And display in datagrid.
    But when I try to use
    public function
    handleFolderContents(event:mx.rpc.events.ResultEvent):void{
    arData=mx.utils.ArrayUtil.toArray(event.result);
    acData=new ArrayCollection(arData);
    input.text=acData.getItemAt(0).id;
    Seems I can’t get data, it always say:
    TypeError: Error #1009: Cannot access a property or method of
    a null object reference.
    2, how to convert data format
    I get data from web service and want to convert it to tree
    structure, as mention below:
    I get:
    <Array>
    <id>111</id>
    <Name>Production1</Name>
    </Array>
    <Array>
    <id>222</id>
    <Name>Production2</Name>
    </Array>
    Convert to:
    <mx:XMLList id="treeData">
    <node>
    <node label="Production1" data="111">
    <node label="Production2" data="222"/>
    </node>
    </node>
    </mx:XMLList>
    Please help me.
    Thanks.

    First, don't specify the package path in the argument
    declaration. Instead import the event object:
    import mx.rpc.events.ResultEvent;
    The docs state this emphatically.
    Second, try "lastResult", in place of "result":
    arData=mx.utils.ArrayUtil.toArray(event.lastResult); // I am
    not positive about this. I maybe recall reading that result was ok
    for the event object, but maybe not.
    Finally, why do you want to convert the xml? You certainly
    could, but it would be a manual process, recursively reading the
    existing xml nodes and building the new structure, but again, why?
    Just use a labelFunction if necessary to display the nodes as
    you wish.
    Tracy

  • A question about comments

    Hi, all,
    I have a question about the comments:
    Program function comments should be included on the block diagram or Front panel, or both. Thanks.

    Many good things have already been mentioned.
    For the Front panel, there should be a clear distinction between toplevel VIs (or any subVIs where the user must interact with the front panel), and subVIs where the front panel is only of interest to the programmer. The needs here are quite different:
    User Interface VIs
    The front panel should be clear and easy to use. All "help" elements, tip strips, etc are geared towards the end user. The icon is irrelevant, because it is typically not even shown. Everything of interest to code maintenance should be on the diagram.
    subVIs
    Here, the front panel can contain a description of what the subVI does, who created it, company and copyright information, version information, limitations (e.g. input A must be >0), URLs or literature references to the algorithm, etc. (Have a look at any of the openG tools!). The "VI properties...documentation" section should be populated. The icon should be descriptive. All controls and indicators should have intuitive names (not just "Numeric 4", or "Array" )
    Comments specific to certain areas of the code should be placed where they apply, especially if the code uses some exotic algorithm that would make the code hard to interpret.
    Use a programming style that is self-documenting. (e.g. Don't unbundle the error cluster check for "equal zero" to switch a case statement. Wire the error cluster directly to the case so you'll get a red/green error case structure. Much more obvious!)
    If these are proprietary VIs with password protected diagrams You should split the comments: Anything of interest to the non-privileged user goes on the front panel, anything else on the diagram.
    In the end, it does not really matters where you place the comments as long as they are easy to find later and still make sense to somebody else 10 years from now. Message Edited by altenbach on 05-30-2005 01:13 PM
    LabVIEW Champion . Do more with less code and in less time .

Maybe you are looking for