Solved

How do I populate Java arrays?

Posted on 2013-01-03
8
201 Views
Last Modified: 2013-01-15
Hi,

I am trying to understand the below code snippets. Can an experts expand upon these code snippets to help me understand how they can be populated and used in a real world example? They are helper methods to get me started writting a lottery program where the user can select up to 20 bets (one bet is a set of six numbers) for a random lottery draw.

private static void printAllBets(int [] [] allBets, int NUMBER_OF_BETS, int BET_SIZE) 
    {
        //use nested for loop to print all bets
        for(int outer = 0; outer < NUMBER_OF_BETS ; outer++) 
        {
            for(int inner = 0; inner < BET_SIZE ; inner++) 
            {
                System.out.println(outer +" " +inner +"\n");
            }//end inner loop
        }//end outer loop
    }
    
    private static void addBet(int [] [] allBets, int [] newBet, int row) 
    {
        //add newBet to allBets at row
        for (int loop = 0;  loop < newBet.length;  loop++) 
        {
            allBets[row][loop] = newBet [loop];
        }//end for loop
    }// end addBet
   
    private static int[] getBet(int [] [] allBets, int row) 
    {
        //get six integers from row
        int [] temp;
        for (int loop = 0; loop < row; loop++)
        {
            //store in array
            temp [loop] = allBets [row] [loop];
            // return array
            return temp;
        }
    }//end method getBet

Open in new window


Thanks.
0
Comment
Question by:aspnet-scotland
  • 3
  • 3
  • 2
8 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 38740979
An array of anything is denoted by the use of square brackets "[]" or multiple square brackets , one pair per array dimension. Arrays start their series at an index of zero. All you have to do is allocate the appropriate type of object or primitive to each index array position.The easiest way to do this is using loops, as in your examples, with nested loops catering for arrays with several dimensions. The alternative is to declare the array with its members all at one time, which may not be appropriate, and can mean extra coding work when it is often easier to let the loop do the work, incrementing the indexes and the values they hold in one instruction.
0
 

Author Comment

by:aspnet-scotland
ID: 38741553
krakatoa,

Could you write some code within my code snippets to describe a basic use of my attached methods? I'm just struggling to understand how the methods can be used, for example, how the below line can be used:

private static void addBet(int [] [] allBets, int [] newBet, int row)

Open in new window


Thanks.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38742016
Not sure that my writing anything is going to clarify things more than they already are, as you already have the code, and you appreciate what it's aiming to do.  But I can say that the above line you quote is a method which takes three parameters - an two-dimensioned int array, a one dimension int array, and then an int. These three values then need to be processed in the method, to by the looks of it - add a bet. The arguments can be used to do anything your application needs or sees fit to calculate - odds, payouts, whatever. Your method can return direct results to whomever called it, and/or store the information in tables or vectors or whatever. I can't see any specific problem here for you, and you are not really mentioning any such.

Best would be for you to complete the logic, and / or use the model in your question to code it up yourself. Once you have that code and it actually yields some results, then we can see which, if any, problems emerge from it and attend to them.
0
 

Author Comment

by:aspnet-scotland
ID: 38742144
So how will I use this to add a bet? For example, I have the below code that prompts the user for 6 lottery numbers then matches these to a 6 random number draw to declare if the user is a winner or not. How would I use the addBet method to allow the user to place multiple bets (each bets is a set of 6 numbers) before the final draw is made? Obviously I would somehow have to pin a username against multiple bets so I can match winners to bets?

import java.util.Scanner;
import java.util.Random;


public class LotteryNumbers
{
 public static void main(String[] args)
 {
  System.out.println( "Play Lottery : 6/49" + "\n");

  // Part 1: Pick six  numbers, between 1 and 49.
  // and put them in an arry of six numbers


  int [] P = new int [6];

  // Create a Scanner input from keyboard
  System.out.println("Part1:  \n");
  System.out.println( "£1 for a line of six numbers. Play!" + "\n");

  System.out.println("Enter your lottery numbers - enter one number at a time.");

   for (int index =0; index <6; index++)
    {
     Scanner keyboard = new Scanner (System.in);
     System.out.print("# " + (index+1) + ": ");
     P[index] = keyboard.nextInt();
       }


         while (
        (P[0] < 1|| P[0] >49)||
              (P[1] < 1|| P[1] >49)||
              (P[2] < 1|| P[2] >49)||
              (P[3] < 1|| P[3] >49)||
              (P[4] < 1|| P[4] >49)||
              (P[5] < 1|| P[5] >49)

              ||

              P[0] == P[1] || P[0] == P[2] || P[0] ==P[3] || P[0]== P[4] || P[0] ==P[5]||

              P[1] == P[2] || P[1] ==P[3] || P[1] ==P[4] || P[1]== P[5] ||

              P[2] == P[3] || P[2] ==P[4] || P[2] ==P[5] ||

              P[3] == P[4] || P[3] ==P[5] ||
              P[4] == P[5]
              )


              {
                  System.out.println( "Error: Please use numbers between 1 and 49 inclusive, and no repititions");

       for (int index =0; index <6; index++)
         {

        Scanner keyboard = new Scanner (System.in);
        System.out.print(" Pick # " + (index+1) + ": ");
           P[index] = keyboard.nextInt();

         }

          }


       // Part 1B": Put your numbers pick in increasing order. Sort the numbers from lowest to highest.


       int startScan, index, minIndex, minValue;

       for ( startScan= 0; startScan <(P.length-1); startScan++)

       {
     minIndex = startScan;
     minValue = P[startScan];

     for ( index = startScan +1; index <P.length; index++)
     {
      if (P[index] < minValue)
      {
       minValue = P[index];
       minIndex =index;
      }

     }
      P[minIndex] = P[startScan];
      P[startScan] =minValue;

     }




  System.out. println ( "This is the sorted list of your  numbers:");

  for (int j =0; j <P.length; j++)

   System.out.print (  P[j] + "  ");



  System.out.println ("End of part 1 \n\n");
        System.out.println();

       // Part 2: Generate 6 random numbers for lottery draw
        System.out.println( "Part2:");

       // Create a Random class object.


        // Let the lottery numbers be:

  int N1, N2, N3, N4, N5, N6 ;   // random numbers

  Random randomNumber = new Random();


        // Let

        N1=1;  N2 = 1;  N3 = 1; N4 = 1; N5=1;  N6= 1;


        while ( N1 <1 ||  N2 <1 || N3 <1 || N4 <1 ||N5 < 1 ||  N6 <1 ||

                 N1==N2 || N1==N3 || N1==N4 || N1==N5 || N1==N6||
                 N2==N3 || N2==N4 || N2==N5 || N2==N6 ||
                 N3==N4 || N3==N5 || N3==N6 ||
                 N4==N5 || N4==N6 ||
                 N5==N6
               )

        {

  N1 = randomNumber.nextInt(49);   N2 = randomNumber.nextInt(49);       N3 = randomNumber.nextInt(49);


        N4 = randomNumber.nextInt(49);     N5 = randomNumber.nextInt(49);        N6 = randomNumber.nextInt(49);

     }


       // Create an array of the Lottery random numbers

       int [] lotteryNumbers  = new int[6];

        lotteryNumbers[0] = N1;    lotteryNumbers[1] = N2;      lotteryNumbers[2] = N3;
        lotteryNumbers[3] = N4;    lotteryNumbers[4] = N5;      lotteryNumbers[5] = N6;



       System.out. println ("The Random-Draw Lottery  Numbers are:");
           for (int j =0; j <lotteryNumbers.length; j++)

           System.out. println ( "#  " + (j+1) + "\t"  + lotteryNumbers[j]);


           System.out. println ();


        // sort the numbers from lowest to highest.

       for ( startScan= 0; startScan <(lotteryNumbers.length-1); startScan++)

       {
     minIndex = startScan;
     minValue = lotteryNumbers[startScan];

     for ( index = startScan +1; index <lotteryNumbers.length; index++)
     {
      if (lotteryNumbers[index] < minValue)
      {
       minValue = lotteryNumbers[index];
       minIndex =index;
      }

     }
      lotteryNumbers[minIndex] = lotteryNumbers[startScan];
      lotteryNumbers[startScan] =minValue;

     }


          System.out. println( "This is the  sorted list of lottery-draw numbers:");

          for (int j =0; j <lotteryNumbers.length; j++)

           System.out. print ( lotteryNumbers[j] + "  ");

           //


        System.out.println( "End of part 2 \n\n");

        System.out.println();

          // Part 3: check lottery numbers - see if P[] == lotteryNumbers[]
          // Let

         System.out.println( "Part3: lottery check!"+ "\n\n");

         int count = 0;

         for ( index = 0; index <6;index++)

          {
     for (int L = 0; L <6; L++)

           if ( P[index] == lotteryNumbers[L])

            count++;
      }


         System.out.println("You matched:  " + count + " number(s)!");

          if( count == 0 )
          System.out.println( "Sorry, You are not a winner this time."+ "\n" );

          if( count == 1 )
          System.out.println( "You  win £1."+"\n" );

          if( count == 2 )
          System.out.println( "You win £2."+"\n");


          if( count == 3)

          System.out.println( "You win £3."+"\n");

          if( count == 4)

          System.out.println( "You win £4."+"\n");

          if( count == 5)

          System.out.println( "You win £50."+"\n");

          if( count == 6)

          System.out.println( "You  win the jackpot of £1000."+"\n");

 }
}

Open in new window


Thanks.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 16

Expert Comment

by:krakatoa
ID: 38742168
So . . . it's not your code, right? Or have you forgotten how it works?
0
 
LVL 6

Accepted Solution

by:
yats earned 500 total points
ID: 38742903
You can probably create a Map
Map<String,int[][]> type
String will represent the UserName and int[][] will represent all the bets for that user.

Now if you wants to add bet for perticular user, you can get the existing bet for that user by saying

int[][] allBets = mapName.get("userName");

Now you can call the addBet() function with the below parameter
addBet(allBets, newBet, row);

newBet is array of numbers entered by user
row - it depends if you wants to update existing of create new row.

But the problem with addBets function is you can't increase the size of allBets.
0
 

Author Comment

by:aspnet-scotland
ID: 38743165
The helper code snippets were given to me to implement within my project, I just wasn't too sure how to use them. I will read in to maps.

"But the problem with addBets function is you can't increase the size of allBets." - this should be ok as there is a maximum of 20 bets before the lottery draw is to be made.

Thanks.
0
 
LVL 6

Expert Comment

by:yats
ID: 38743478
In that case the approach I have suggested with work fine.

Are you expecting anything else??
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
powerN  challenge 3 49
changePi Challenge 15 77
Cipher Configuration on Apache HTTPD 4 24
HSSFWorkbook cannot be resolved error 10 23
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now