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…

Tuesday, March 31, 2015

Interest Calculator

The idea behind this small program is to tell you how many subscribers you would have after a given number of days if you assume compound interest rate growth of 1% every day. Here’s the original code provided by the video that uses a for loop.

class apples{
       public static void main(String args[]){        
              double amount;
              double principal = 10000;
              double rate = .01;
             
              for(int day=1; day<=20; day++){
                     amount = principal*Math.pow(1 + rate, day);
                     System.out.println(day + "    " + amount);
              }
             
       }
}

Based on the compound interest formula of  Amount = Principal*(1+rate)^time - this tells you how much your subscribership grows over 20 days. By now I’m sort of getting the hang of making these modular and generic though, so I want to see if I can make it so you input an initial amount, an interest rate, and run it for any number of days you want.
First thing to do is import the Scanner and make it so the program can receive input

              import java.util.Scanner;

              class apples{
                     public static void main(String args[]){
                            Scanner input = new Scanner(System.in);

Next we need to modify it so the principal and rate can be entered, and make an empty integer variable for time to indicate the number of days you want it to calculate - while we’re at it we may as well make the code more expressive to the user.

              System.out.println("Interest rate calculator");
              System.out.println("Enter the principal balance:");
              double principal = input.nextDouble();
             
              System.out.println("Enter the interest rate: ");
              double rate = input.nextDouble();
             
              System.out.println("Enter the number of days you want to run the calculator for: ");
              int time = input.nextInt();
             
              double amount;

Now to modify the for loop to accept the time variable, and to display the principal amount for the 0th day.
              System.out.println(0 + "   " + principal);
              for(int day=1; day<=time; day++){
                     amount = principal*Math.pow(1 + rate, day);
                     System.out.println(day + "    " + amount);
              }

And it works. It asks me for the principal balance, then the interest rate, then the number of days I want it to run, then it spits out the information in a neat little faux formatted table.

I wondered what would happen if you put 0 for the time variable and was pleasantly surprised to find that the program just sat there without doing anything. I was half expecting an error, but dug a little deeper. Setting the code to start at day 5 and the time to 2, and the calculator provides no information. Even better, when I try to modify the code to do this:

              for(int day=5; day<=day+time; day++){
                     amount = principal*Math.pow(1 + rate, day);
                     System.out.println(day + "    " + amount);
              }


 With the same input of 2 days for time, the for loop runs forever and outputs “infinity” as the new amount, up to more than 100k times in a few seconds. So the expected integer input for day must be higher than whatever the initial integer is hard coded in as. At this point I’m not sure if it’s a limitation of the for loop or something else – either way it’s a good lesson to start at 1 when setting up loops that incrementally increase.

Averaging Program - Grades

Learning Java...

Continuing off from last time, I've started learning Java and using some video tutorials to make basic programs and run them. As noted before, I work in IT but have little to no programming experience beyond the HTML/CSS necessary to edit existing web pages.

The video gave the premise of a teacher using a simple averaging program for finding out the average of 10 grades, and used the following code to accomplish it
import java.util.Scanner;

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

I saw this and immediately thought that it seemed a bit clunky, not as code but as a teaching tool. The output that you see gives you no indication of what’s going on in the code until the end, which made it harder to track what was happening.

The first change I made was to consolidate the variables and make them doubles instead of integers. since a grade can be a percentage with a decimal.
              double total = 0;
              double grade, average;


Next I tried to put in a println statement that would let you know which grade you’re working on as the counter increases.
                     while (counter < 10){
                            System.out.println("Enter grade " + counter);
                            grade = input.nextInt();
                            total = total + grade;
                            counter++;
                     }

Then I realized that the counter started at 0 instead of 1, which made it a bit weird. My first attempt to fix this resulted in a clunky increment increase for the println, then a decrease to undo the increment increase, and then an increase to move the counter up for the next iteration of the while statement.
                     while (counter < 10){
                            System.out.println("Enter grade " + ++counter);
                            grade = input.nextInt();
                            total = total + grade;
                            counter--;
                            counter++;
                     }

That worked, but it still seemed a bit odd. Then it hit me that if I changed the while statement to say <= instead of just < I could set the counter variable to start at 1 and still get 10 grades entered without the need to add, then subtract, then add again.
                     int counter = 1;
                    
                     while (counter <= 10){
                            System.out.println("Enter grade #" + counter);
                            grade = input.nextInt();
                            total = total + grade;
                            counter++;
                     }

The final code works better for me as a teaching tool because it asks for each grade by number, and then produces the result at the end, but it doesn't use any code or tricks that haven’t been taught by the video series up to this point.  The connection between what happens after every input is much clearer.

From my own perspective I like the code to respond to input, or ask for what it wants rather than just sit there and expect you to know what to do.

Else/If Program

After working through the introductory videos with what programs to use (already had Notepad++, which I absolutely love for it’s color coding), I finally started getting into creating some small programs.

Here’s the final code from the video
class apples {
       public static void main(String args[]){
                     int age = 45;
             
                     if (age >= 60)
                            System.out.println("You are a senior citizen");
                     else if (age >=50)
                            System.out.println("You are in your 50's");
                     else if (age >=40)
                            System.out.println("You are in your 40's");
                     else
                     System.out.println("You are a young buck");        
       }

}

This is where I asked why the age was set as a static variable if you’re going to teach the idea behind else/if – at this point we've already learned how to import Scanner, input text from the keyboard and store it as a variable, why not make this small piece of code do exactly that?

The first change I made was to add the Scanner and allow for keyboard input.
import java.util.Scanner;

class apples {
       public static void main(String args[]){
              Scanner input = new Scanner(System.in);        
             
              int age = 45;
             
              if (age >= 60)
                     System.out.println("You are a senior citizen");
              else if (age >=50)
                     System.out.println("You are in your 50's");
              else if (age >=40)
                     System.out.println("You are in your 40's");
              else
                     System.out.println("You are a young buck");  
       }

}

Now that we can input text we need to set the variable of age to be an empty integer and assign it be whatever is input to the program
import java.util.Scanner;

class apples {
       public static void main(String args[]){
              Scanner input = new Scanner(System.in);
              int age;
             
              age = input.nextInt();
             
              if (age >= 60)
                     System.out.println("You are a senior citizen");
              else if (age >=50)
                     System.out.println("You are in your 50's");
              else if (age >=40)
                     System.out.println("You are in your 40's");
              else
                     System.out.println("You are a young buck");
       }

}

Then Lastly let’s give the user a message that tells them what to do when the program starts.
import java.util.Scanner;

class apples {
       public static void main(String args[]){
              Scanner input = new Scanner(System.in);
              int age;
             
              System.out.println("Enter your age: ");
              age = input.nextInt();
             
              if (age >= 60)
                     System.out.println("You are a senior citizen");
              else if (age >=50)
                     System.out.println("You are in your 50's");
              else if (age >=40)
                     System.out.println("You are in your 40's");
              else
                     System.out.println("You are a young buck");
       }

}


Now when the program is run it first asks you what your age is and allows you to input it. Based on what you put it the else/if statement will respond accordingly.