Thursday, April 2, 2015

Random number generator

Here's the code used in the video for random number generation.

import java.util.Random;

class apples{
       public static void main(String[] args){
             
              Random dice = new Random();
              int number;
             
              for(int counter=1; counter<=10; counter++){
                     number = dice.nextInt(6);
                     System.out.println(number + "  ");
              }
             
       }
}

The dice.nextInt(6); line is where the number of random numbers you want to work with is input based on a dice roll, meaning the for loop will only produce a single random number on every iteration. However this version only generates integers from 0 to 5 instead of 1 to 6. I was informed the other day by a programmer friend (Hi Alex, you rat bastard) that all counters start at 0, and that this is intentional and shouldn't be messed with unless there’s a good reason. If you want to modify the output so that it doesn't return zeroes that’s usually done separately, like so.

import java.util.Random;

class apples{
       public static void main(String[] args){
             
              Random dice = new Random();
              int number;
             
              for(int counter=1; counter<=10; counter++){
                     number = 1+dice.nextInt(6);
                     System.out.println(number + "  ");
              }
             
       }
}

I see one further change that could be justified based on putting all counters to zero, namely changed the for loop to read:

for(int counter=0; counter<10; counter++)

Which is still 10 numbers but there’s no need to list them.

So adding 1 to the random number generation makes it 1-6 instead of 0-5, which is useful. Going back I wanted to fix my previous code to comply with this (improved? standard?) practice and made the grade averaging program follow the same logic.

import java.util.Scanner;

class apples{
       public static void main(String[] args){
              Scanner input = new Scanner(System.in);
             
        double total = 0;
        double grade, average;
        int counter = 0;
      
        while (counter < 10){
            System.out.println("Enter grade #" + ++counter);
            grade = input.nextInt();
            total = total + grade;
     }
       
        average = total/10;
        System.out.println("Your average is " + average);
             
             
       }
}


Basically I just make the counter increment up by one just prior to displaying the counter, and changed the <=10 to just <10. I didn’t find this terribly difficult, but I’m about to start arrays so…