Help on array

Hi, I want to sort an array which contains Strings (sort according to alphabetical order...)
after i sort the array...i want to read it at it's original order too...
that mean's i want to have 2 set of array.....1 with the original order...1 with the sorted order..
how do i do that?
let's say i have a container class Club with an array of Names(type String), and a client class...
with a Club object memberList.how do i do that?
thank you.

that mean's i want to have 2 set of array.....1 with
the original order...1 with the sorted order..OK, how about
  ArrayList origArray = ... whatever ...;
  ArrayList sorted = new ArrayList(origArray);
  Collections.sort(sorted);Now, origArray still has your data in the original order, sorted has it in the sorted order. Note: both are pointing to the same elements.

Similar Messages

  • Need help for array counting

    Any help for array question
    Hello to All:
    I want to tally or count some of the elements that I have in array but not sure how.
    I have for example: int myArray[] = {90,93,80,81,71,72,73,74};My objective is to tally all of the 90's, tally all of the 80's and tally all of the 70's.
    So, the result that I want to have would look something like the following:
    System.out.println ("The total tally number of 90's is " 2 );
    System.out.println ("The total tally number of 80's is " 2 );
    System.out.println ("The total tally number of 70's is " 4 );I do not want to add these numbers, just want to count them.
    Also I want to use a "forloop" to achieve the result intead of just declaring it at 2 or 4 etc..
    Any help Thankyou

    [u]First , This is not exactly what I have to
    do for homework. There is a lot more, a lot more
    involved with the program that I am working on.
    Second, this is an example, an example, an
    example of something that I need to achieve.
    Third, you are asking for a code, to me that
    sounds as if your asking for homework. Fourth,
    I did not ask for any rude comments. Fith, in
    the future please do not reply to my messages at ALL
    if you can not help!!!!
    Sixth, We did not ask for lazy goofs to post here.
    Seventh, In the future please do not post here. Take a hike - there's the virtual door.

  • Help with array's again

    Hello again
    I know im probably getting on peoples nerves now, but im still working on my lottery simulation. Ive tried different techniques, all of which have worked so far but now im trying a different way and have encountered a problem i cannot de-bug.
    Please can you have a look at my code, its probably obvious to most of you experts.
    int[] winners = new int[5];
    winners[0] = Lotto.drawBall();
    int num = Lotto.drawBall();
    for(int counter = 1; counter<5;){
        while(counter <= winners.length){
            if(num==winners[0] || num==winners[1] || num==winners[2] || num==winners[3] || num==winners[4]){
                num = Lotto.drawBall();
            else{
                winners[counter] = num;  //here is where my exception occurs
                counter++;
    System.out.print(winners[0]);
    System.out.println();
    System.out.print(winners[1]);
    System.out.println();
    System.out.print(winners[2]);
    System.out.println();
    System.out.print(winners[3]);
    System.out.println();
    System.out.print(winners[4]);I get an Array index out of bounds exception but i cannot see how.
    Please can you help me again??
    D_H

    int[] winners = new int[5];
    winners[0] = Lotto.drawBall();
    int num = Lotto.drawBall();
    for(int counter = 1; counter<5;){
    while(counter <= winners.length){ /*Here you should use counter < winners.length*/
    if(num==winners[0] || num==winners[1] ||
    s[1] || num==winners[2] || num==winners[3] ||
    num==winners[4]){
    num = Lotto.drawBall();
    else{
    winners[counter] = num;  //here is where
    re is where my exception occurs
    counter++;
    System.out.print(winners[0]);
    System.out.println();
    System.out.print(winners[1]);
    System.out.println();
    System.out.print(winners[2]);
    System.out.println();
    System.out.print(winners[3]);
    System.out.println();
    System.out.print(winners[4]);I get an Array index out of bounds exception but i
    cannot see how.
    Please can you help me again??
    D_Hcheck the while condition you are using count until it is equal to 5

  • Noob needs help with array manipulation

    First off, I'd like to say hello to eveybody!
    I'm trying to figure out how to search for a value in an array, delete the first occurence of it, and shift the rest of the array down one. Can anyone point me in the right direction of an algorithm, mabey?
    Any help is most appreciated!

    first of all, let me comment that for this purpouse, you're better using the ArrayList class.
    anyway, you would need to make a temporary array inside a method, and traverse the array in question using a loop. most people use a for loop.
    Then, put all the values of the old array into the temporary one, except for the one you dont want.
    after the loop, set the old array to equal the temporary array.

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

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

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

  • Need Help with Arrays/Text

    I'm trying to create a flash program that uses it's own code to send and create images. Each square has a colour and that colour gets added into the array. A black, then grey, then white is:
    filecode = ["Bl", "Gr", "Wh"];
    That works fine, but when I try to paste it into an Input text box it will only fill in the first part of the array.
    filecode = ["Bl,Gr,Wh"];
    So the program has NO idea what I want.
    The only ways I can think of fixing this is by putting in 402 text boxes to suit every box...But every one of them needs a Variable Name.
    Or by sending the information straight into the array. But this way you are just looking at what you just drew, and that is not at ALL practical.
    Helping me with this headache will be greatly apprectiated.
    FlashDrive100.

    If you can explain the first part of your posting it might become a little clearer what you are trying to do and what isn't working... particularly this...
    " when I try to paste it into an Input text box it will only fill in the first part of the array."
    I can't speak for anyone else, but at this point, I share your file's problem... not knowing what you want.

  • Please help, 2D Array of Vectors and Incompatible types :(

    I have a 2D array of vectors called nodeLocations but when I try and access the vector inside I get a compile error.
    My code is something like this:
    nodeLocations[j].addElement(noArc)
    My editor picks up that its a Vector and shows me addElement as an acceptable entry to put after the "." yet the compiler says:
    "addElement(java.lang.Object) in java.util.Vector cannot be applied to (int)"
    Can someone please help?
    Thank you in advance.
    also a related problem:
    I get inconvertible types (says int required) when I try and get an element from a vector stored in a 2D Array. I know that it comes out as an object and so should be cast but it does not seem to work. My code is as follows:
    else if (((int)(nodeLocations[nodeNumber][adjNodeNumber].elementAt(0))) != distance)
    I would appreciate any help anyone can give.
    Similar errors to the above two happen when
    I try a push with a Stack in a vector.
    I try to get something out of the stack inside the vector.

    The Vector class's addElement() method requires an Object parameter. It appears that you're trying to add an int to the Vector. You'll need to create an Integer object and place that into the vector (see sample below) or use the pre-release version of JDK 1.5 which provides autoboxing capabilities.
    int z = 5;
    Integer x = new Integer(z);
    nodeLocations[j].addElement(x);

  • Help with arrays and Exception in thread "main" java.lang.NullPointerExcept

    Hi, I have been having trouble all day getting this array sorted and put into a new array. I think it is something simple with my nested loops in sortCityArray() that is causing the problem. Any help would be greatly appreciated. The error is thrown on line 99 at Highway.sortCityArray(Highway.java:99)
    import java.util.Scanner;
    import java.io.*;
    import java.util.Arrays;
    public class Highway
    private String[] listOfCities=new String[200];
    private City[] cityArray=new City[200];
    private City[] sortedCityArray=new City[200];
    private String city="";
    private String city2="";
    private String fileName;
    private City x;
    private int milesToNextCity;
    private int milesAroundNextCity;
    private int speedToNextCity;
    public Highway(String filename)
    String fileName=filename;//"I-40cities.txt";
           File myFile = new File(fileName);
           try {
           Scanner scan=new Scanner(myFile);
           for(int i=0; scan.hasNextLine(); i++){
           String city=scan.nextLine();
           String city2=scan.nextLine();
           int milesToNextCity=scan.nextInt();
           int milesAroundNextCity=scan.nextInt();
           int speedToNextCity=scan.nextInt();
                   if(scan.hasNextLine()){
              scan.nextLine();
           cityArray=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    //return cityArray;
    /*public City[] doCityArray(){
    File myFile = new File(fileName);
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
    String city=scan.nextLine();
    String city2=scan.nextLine();
    int milesToNextCity=scan.nextInt();
    int milesAroundNextCity=scan.nextInt();
    int speedToNextCity=scan.nextInt();
         if(scan.hasNextLine()){
              scan.nextLine();
    cityArray[i]=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    return cityArray;
    public City[] sortCityArray(){
    sortedCityArray[0]=new City(cityArray[0].getCity(),cityArray[0].getNextCity(),cityArray[0].getLengthAB(),cityArray[0].getLengthAroundB(),cityArray[0].getSpeedAB());
    for(int j=0; j<cityArray.length; j++ )
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
    /*     for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    //     j++;
    System.out.println(sortedCityArray[0].getCity());
    System.out.println(sortedCityArray[0].getNextCity());
    System.out.println(sortedCityArray[0].getLengthAB());
    System.out.println(sortedCityArray[0].getLengthAroundB());
    System.out.println(sortedCityArray[0].getSpeedAB());
    System.out.println(sortedCityArray[1].getCity());
    System.out.println(sortedCityArray[1].getNextCity());
    System.out.println(sortedCityArray[1].getLengthAB());
    System.out.println(sortedCityArray[1].getLengthAroundB());
    System.out.println(sortedCityArray[1].getSpeedAB());
    System.out.println(sortedCityArray[2].getCity());
    System.out.println(sortedCityArray[2].getNextCity());
    System.out.println(sortedCityArray[2].getLengthAB());
    System.out.println(sortedCityArray[2].getLengthAroundB());
    System.out.println(sortedCityArray[2].getSpeedAB());
    System.out.println(sortedCityArray[3].getCity());
    System.out.println(sortedCityArray[3].getNextCity());
    System.out.println(sortedCityArray[3].getLengthAB());
    System.out.println(sortedCityArray[3].getLengthAroundB());
    System.out.println(sortedCityArray[3].getSpeedAB());
    System.out.println(sortedCityArray[4].getCity());
    System.out.println(sortedCityArray[4].getNextCity());
    System.out.println(sortedCityArray[4].getLengthAB());
    System.out.println(sortedCityArray[4].getLengthAroundB());
    System.out.println(sortedCityArray[4].getSpeedAB());
    return cityArray;
    /*public String[] listOfCities(){
    File myFile = new File("I-40cities.txt");
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
         String city=scan.nextLine();
         city=city.trim();
    scan.nextLine();
    scan.nextLine();
         listOfCities[i]=city;
         System.out.println(listOfCities[i]);
    catch (Exception e) {
    System.out.println(e);
    return listOfCities;
    public static void main(String args[]) {
    Highway h = new Highway("out-of-order.txt");
    h.sortCityArray();

    the ouput is perfect according to the print lines if I use (increase the int where j is in the loop manually by one) :
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[0].getNextCity().equals(cityArray.getCity())){
              sortedCityArray[0+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[1].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[1+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[2].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[2+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[3].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[3+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    But I cant do this for 200 elements. Are the loops nested right?
    Edited by: modplan on Sep 22, 2008 6:49 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help with arrays in PHP

    Hi All,
    I have created a page that shows thumbnail images of all
    images in a
    given directory. Here is the function that searches the
    directory and
    builds an array of qualified files:
    > function getImages($dir) {
    > $directory = new DirectoryIterator($dir);
    > $fileTypes =
    '#\.jpg$|\.jpeg$|\.gif$|\.png$|\.JPG$|\.GIF$|\.PNG$#i';
    > $filtered = new RegexIterator($directory, $fileTypes);
    > $array = array();
    > foreach ($filtered as $item) {
    > $array[] = $item->getFilename();
    > }
    > return new ArrayIterator($array);
    > }
    >
    > // get an ArrayIterator of filenames and the total
    number:
    > $images = getImages('../images/images_news/');
    > $totalImages = $images->count();
    Here is the HTML and PHP used to display the images (I'm
    excluding code
    that is specific to the paging function):
    > // Implement offset and files per page
    > foreach (new LimitIterator($images, $offset,
    $filesperpage) as
    > $image) { ?>
    > <div class="imgcont">
    > <div class="imgholder">
    > <img src="../images/images_news/<?php echo $image;
    ?>"
    > alt="<?php echo $image; ?>" height="55"
    class="center" />
    > </div>
    > <p class="smallname"><?php echo $image;
    ?></p><br />
    > </div>
    > <?php } ?>
    > <div class="clear"><br />
    My question is this. I need to provide a way to delete images
    that will
    no longer be needed. Actually, I need to be able to delete
    the main
    image and the thumbnail image, each of which is in a separate
    directory. What I don't know is how this type of thing is
    normally done
    (I don't want the FTP route because I don't want a client
    messing about
    in the directory structure). And what I don't understand is
    how to
    select one or more files to delete when they were produced by
    an array.
    For ease of use, it would be nice if I could add a checkbox
    that the
    user could check to indicate that the image(s) should be
    deleted. I
    just can't figure out how to select the file(s). I sure hope
    this is
    not one of those simple things that will make me hide my head
    in shame.
    Any help would be most appreciated.
    Brett

    Brett wrote:
    > the thumbnail images now have _tmb inserted between
    > the file name and the extension. So when deleting I keep
    getting
    > warnings that the file mypic001.jpg cannot be found in
    the thumbs
    > directory. How do I get the _tmb into the file name?
    foreach ($_POST['images'] as $image) {
    unlink($mainImgDir . $image);
    $pos = strrpos($image, '.');
    $thumb = substr($image, 0, $pos) . '_tmb' . substr($image,
    $pos);
    unlink($thumbsDir . $thumb);
    > By the way, you used unset() where I think you meant
    unlink().
    Yes, I did. Sorry about that.
    > Finally, I have discovered that if I upload a file named
    Ti301.JPG, I
    > get Ti301.JPG001_thb.jpg. It seems that the strtolower()
    function in
    > getNextFilename5.php is not converting the uppercase
    extension, it is
    > just adding the incremented number plus _tmb and the new
    extension. Any
    > ideas about how to correct that?
    That shouldn't be happening, but I don't have time to look
    into that
    now. Sorry.
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS3" (friends of
    ED)
    Author, "PHP Solutions" (friends of ED)
    http://foundationphp.com/

  • Help using arrays in java

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

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

  • Help with array program!!

    hi friends
    i am a new comer to java and I have been studying Arrays recently. I came across this program on the internet ( thanks to Peter Williams)
    package DataStructures;
    import java.util.NoSuchElementException;
    * An array implementation of a stack
    * @author Peter Williams
    public class StackArray implements Stack {
    private int top; // for storing next item
    public StackArray() {
    stack = new Object[1];
    top = 0;
    public boolean isEmpty() {
    return top == 0;
    public void push(Object item) {
    if (top == stack.length) {
    // expand the stack
    Object[] newStack = new Object[2*stack.length];
    System.arraycopy(stack, 0, newStack, 0, stack.length);
    stack = newStack;
    stack[top++] = item;
    public Object pop() {
    if (top == 0) {
    throw new NoSuchElementException();
    } else {
    return stack[--top];
    interface Stack {
    * Indicates the status of the stack.
    * @return <code>true</code> if the stack is empty.
    public boolean isEmpty();
    * Pushes an item onto the stack.
    * @param <code>item</code> the Object to be pushed.
    public void push(Object item);
    * Pops an item off the stack.
    * @return the item most recently pushed onto the stack
    * @exception NoSuchElementException if the stack is empty.
    public Object pop();
    class StackDemo {
    public static void main(String[] args) {
         Stack s = new StackArray();
         // Stack s = new StackList();
         for (int i = 0; i < 8; i++) {
         s.push(new Integer(i));
         while (!s.isEmpty ()) {
         System.out.println(s.pop());
    what baffles me is as below:
    there is an 'if' construct in the push method, which talks about if(top == stack.length)
    I fail to understand how top can at any time be equal to stack.length.
    Could you help me understand this program?
    a thousand apologies and thanks in advance

    figurativelly speaking:
    if you take an array and put it standing on your tesk, so that start of array points to floor, and end of array points to roof, then you can start filling that array as stack.
    if you put books into stack, then you push (put) them on top of the stack, so the first book ever but into stack is adiacent to array element with index zero (0) and then second book in stack would be adiacent to array element that has index one (1) and so on.
    if you have array of size 5, then fift book in stack would be adiacent to array element with index four (4)
    after pushing that Object to stack, the top variable will get incremented (top++ in code) and be equal to size of array.
    however, if you would like to push another Object to stack, then it would fall over the end of the array, so longer array is needed...

  • Need help with Arrays

    Hey guys, I'm a beginner programmer and I'm having a bit of a tough time with arrays. I could really use some help!
    What I'm trying to do is roll one die and then record the rolls.
    Here is my sample I/O:
    How many times should I roll a die?
    -> 8
    rolling 8 times
    2, 1, 5, 6, 2, 3, 6, 5
    number of 1's: 1
    number of 2's: 2
    and so on....
    Here is my incomplete code at this moment:
    //CountDieFaces.java
    import java.util.Scanner;
    import java.io.*;
    import library.Gamble;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        Scanner scan = new Scanner(System.in);
        int[] faceCount= {0,0,0,0,0,0,0};
        int dice;
        System.out.println("How many times would you like to roll the die?");
        int dieCount = scan.nextInt();
        int dieRoll = Gamble.rollDie(); // Main calling class method
        int count = 1;
        while(count < dieCount)
            System.out.println(faceCount[count]);
            count++;
    }Here is the gamble library:
    //Gamble.java
    package library;
    public class Gamble
         // returns 1, 2, 3, 4, 5, or 6
         public static int rollDie()
              int dieRoll = (int)(Math.random()*6)+1;
              return dieRoll;
    }and here are the errors I have so far:
    ----jGRASP exec: javac -g CountDieFaces.java
    CountDieFaces.java:19: <identifier> expected
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:19: illegal start of type
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:25: illegal start of type
         while(count < dieCount)
         ^
    CountDieFaces.java:25: > expected
         while(count < dieCount)
         ^
    CountDieFaces.java:25: ')' expected
         while(count < dieCount)
         ^
    CountDieFaces.java:26: ';' expected
         ^
    CountDieFaces.java:27: illegal start of type
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ';' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: invalid method declaration; return type required
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ']' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ')' expected
              System.out.println(faceCount[count]);
    I'm really confused with how a the gamble library gets put into the array, so any help is appreciated! Also if anyone could explain the errors to me, I would really appreciate it.
    thanks in advance,
    wootens
    Edited by: Wootens on Oct 18, 2010 8:55 PM

    D'oh!
    Thanks you guys, fixed that. Although I'm having trouble with storing the die roll in the array. Any suggestions?
    java.io.*;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        public static void main(String[] args)
            Scanner scan = new Scanner(System.in);
            int[] faceCount= {0,0,0,0,0,0};
            int dice;
            System.out.println("How many times would you like to roll the die?");
            int dieCount = scan.nextInt();
            int dieRoll = rollDie(); // Main calling class method
            int count = 0;
            while(count < dieCount)
                System.out.println(faceCount[dieRoll]);
                count++;
        public static int rollDie()
            int dieRoll = (int)(Math.random()*6)+1;
            return dieRoll;
    }Wootens

  • Hi all, i need Help in Arrays

    Hi All,
    I have some problems on the below questions scenario;
    Program 1
    You are to write a program using a method other than main. The program is to
    �     collect monthly rainfall figures for 12 months
    �     pass the total annual rainfall to another method which calculates the average monthly rainfall and returns it to the main method
    �     calculate the variation of each month from the average (as a positive)
    �     display the results
    Sample input screen
    Enter rainfall for month 1:     13.3
    Enter rainfall for month 2:      14.9
    Enter rainfall for month 3:      14.7
    Enter rainfall for month 4:      23.0
    etc for the 12 months jan-dec
    After the 12 months of data has been collected as report as follows is displayed:
    Annual Rainfall Report
    Monthly average: 15.04mm
    Month          Rainfall     Variation
    January          13.3          1.73
    February          14.9          0.13
    March          14.7          0.33
    April          23.0          7.97
    etc for the year�
    Problem 2
    You are to make major improvements to last week�s program.
    The format of your program and some key elements should be as follows:
    public class Rainfall
         public static void main()
              Create an array for monthly rainfall
              Loop to collect rainfall figures from user and store in array
              Loop through rainfall array
                   Call printRainfall method passing month number, rainfall for                          that month, and average as parameters
         printRainfall method
              Create an initialiser list array of month names
                   (ie hard code the month names in your program)
              Print report headings
              Use the parameters to access month names array and print report                          detail line
    I have problems with the Problem 2 which i can't loop up the input values and printouts using aarays to do it.
    Can anyone out there help me to solve the problems ? If possible, please reply me at my email @ [email protected] .Lotsa thanks.
    Thanks and Regards.

    So why don't you tell us exactly what's going wrong and show us the code where it's going wrong.

  • URGENT   HELP::: returning array of non built in datatypes

    Folks,
    I am trying to implement webservices in weblogic7.0 sp2. We have written a simple
    class(say ClassA) which uses another bean as a user defined data type(ClassB implements
    serializable). I am able to create a webservice if one of the method in ClassA
    returns the object of classB.I am getting an error while creating the web-services.xml
    file using ant tool if same method in ClassA returns array of ClassB.It says
    corresponding type is not found in the types.xml. I created types.xml using ant
    tool too.
    Does weblogic7.0 SP2 support returning array of objects in webservices?
    Any suggestions and immediate response is highly appreciated.
    Thanks,
    Kamal.

    Bruce,
    You understand the question correctly..Thanks for the help... it works now.
    Thanks,
    Kamal.
    Bruce Stephens <[email protected]> wrote:
    Hi Kamal,
    If I understand your question correctly, yes, you should be able to do
    this. You will need to create your own implementation of the
    javax.xml.rpc.holders.Holder interface. See:
    http://edocs.bea.com/wls/docs70/webserv/implement.html#1054236 for
    details.
    If that's not what you are asking, could you post a simple test case?
    HTHs,
    Bruce
    BTW, for URGENT issues, please use our excellent support folks:
    http://support.bea.com
    [email protected]
    kamal wrote:
    Folks,
    I am trying to implement webservices in weblogic7.0 sp2. We have writtena simple
    class(say ClassA) which uses another bean as a user defined data type(ClassBimplements
    serializable). I am able to create a webservice if one of the methodin ClassA
    returns the object of classB.I am getting an error while creatingthe web-services.xml
    file using ant tool if same method in ClassA returns array of ClassB.Itsays
    corresponding type is not found in the types.xml. I created types.xmlusing ant
    tool too.
    Does weblogic7.0 SP2 support returning array of objects in webservices?
    Any suggestions and immediate response is highly appreciated.
    Thanks,
    Kamal.

  • Help with arrays & counting characters in arrays

    I am trying to figure out how to count how many times each characters appears in the array (but I have to do all the counts at once).
    I am supposed to store the counts in an int[] array of 27 elements (26 letters & an extra count for everything else). How would I go about declaring the array, allocating it, & then setting each of the 27 elements zero?
    Thanks so much the help.
    public class CharCount {
         public static void main(String[] args) {
              new CharCount().process();
         public void process() {
             // This declares an array of char and then assigns it a value.  The value comes from another one
             // of my secret programs.
             char[] countThese = Lab8.simple();
             printChars(countThese);
             for (int count =0; count < countThese.length; count++) {
              System.out.println(countThese[count]);
        // This method should print the characters in the array called print, one-by-one
        // Use a println ONLY after all the chars have been printed.
        public void printChars(char[] print) {
        public int charToInt(char ch) {
         if (ch >= 'A' && ch <= 'Z')
             return ch - 'A';
         else if (ch >= 'a' && ch <= 'z')
             return ch - 'a';
         else return 26;
    }

    I take it the charToInt method was given to you. If you don't know what it does, it will give you a value from 0 to 26 depending on what char you pass as a parameter. So if you pass an 'a' or an 'A' it will return 0, 25 for 'z' or 'Z' and 26 for anything else. You use this value to access an array an increment the value (the number of times that letter has occured.
    int value = charToInt('a');
    arr[value]++;
    System.out.println("Number of a's = " + arr[0]);

  • Help with array / indexed property

    Hi,
    I am trying to save the value of multiple dropdowns in the Session Bean. Therefore, I created an index property "rule" in the Bean.
    Each time the page is loadad, a different dropdown appears depending on the previous choices. If the ok button is clicked, the action is performed to save the current dropdown value in the index property:
    public String button1_action() {
    int cnt = 1;
    // if page was loaded before, replace count
    if (getAdminBean().getCount() > 0) {
    cnt = getAdminBean().getCount() +1;
    } else {
    // save current count in Session
    getAdminBean().setCount(cnt);
    setValue("#{AdminBean.rule[cnt-1]}", selectme.getValue());
    This is the error message:
    Exception Details: javax.faces.el.PropertyNotFoundException
    Error setting property '-1' in bean of type null
    Possible Source of Error:
    Class Name: com.sun.faces.el.PropertyResolverImpl
    File Name: PropertyResolverImpl.java
    Method Name: setValue
    Line Number: 153
    I have played around and even the following code would not work to save a value at the first position of the index property:
    setValue("#{AdminBean.rule[0]}", selectme.getValue());
    Can anyone help?
    Thanks,
    Nils

    You can not set the index as you use here i.e
    #{AdminBean.rule[cnt-1]}
    is not correct. Because in JSF the "[" is used for some other purpose.
    I would suggest you to use another property called "index"
    setValue("#{AdminBean.index", cnt-1);
    setValue("#{AdminBean.rule", selectme.getValue());
    Inside the session bean, in the method setRule get the index (already set) and place your value in the correct indexed array.
    Same logic you can use to get the value too
    setValue("#{AdminBean.index", cnt-1);
    getValue("#{AdminBean.rule");
    the method getRule() should get the value for the index and return it.
    - WInston
    http://blogs.sun.com/roller/page/winston?catname=Creator

Maybe you are looking for