Tuesday, May 26, 2015

Final Project - Secret Messager

Download the application here.

This program stems from the Braille translator I made a month or so ago, and utilizes a similar kind of array system to sort character information.

Basically, to "encode" a user's input, the encoder class will create a randomized alphabet (including numbers and symbols), switch each character in the user input with its randomized character, put that into the output, and then stick the full randomized alphabet at the end of the output for the decoder to use. Since this is randomized each time, it would be relatively difficult to crack under normal circumstances if you don't know the format of the original non-randomized alphabet array.

To "decode" the encoded message, the decoder splits the encoded message into the actual user's input and the randomized alphabet that was stuck at the end (it is able to do this because the length of the randomized alphabet doesn't change). It then basically does what the encoder did, but in reverse - flip every mixed up character with the original alphabet, essentially unscrambling the message.

Here's the program in action:





The decoded message, as of v3.1, will now also copy to the clipboard.


Sunday, April 26, 2015

Braille Maker

I'm just uploading this for my own sake; it has nothing to do with recursion or web development. I made a program that translates what you type into Braille, with a chunk of commented-code at the top that explains how Braille works. It mostly utilizes nested for-loops.

You can find this code here.

If some of the characters in the Braille arrays look funny, or just show up as boxes, it's probably because whatever browser/computer you're using does not support Unicode Braille patterns. The program itself should still technically work, however.




Here's that output blown up a bit to improve readability:
"Hello, world!", in Braille, is: ⠠⠓⠑⠇⠇⠕⠂⠀⠺⠕⠗⠇⠙⠖

There are numerous online converters for Braille that can be used to check my program, and it should work for most normal characters.

Tuesday, April 21, 2015

Another recursion post - Character Search!

This is related to another CodingBat recursion problem. Specifically, this one.

Basically, it recursively searches through a number to find a specific digit, which, in this case, is 7. It then counts how many times that digit is found in the number, if any (e.g. 127 would return 1).

I made this into a program that, instead of just searching through numbers for a given digit, can search through any sort of string for a given character (which, in the program, is technically just a string of length 1). While the task could be accomplished with a for loop, I decided to keep with the format of the CodingBat problem, only changing a few if statements to deal with strings as opposed to numbers.

The program can be found here.

Interestingly, it was easier to comprehend the recursive function of the program in terms of strings than it was with numbers. For example, getting the last digit in a number requires the modulo operator and the number 10. So, 126 % 10 = 6.  When doing the same thing with strings, all you need is a substring - specifically, a substring from str.length() - 1 to str.length()

Similarly, to get a number to change to all the digits but the final one, you have to divide by 10, and be sure to avoid floats/doubles: 126 / 10 = 12. With substrings, you just need to go from 0 to str.length() - 1

All of these transformations are needed in the recursive function. After reformatting it for strings and implementing a user input system, the program was pretty much complete. I had a little trouble getting multiple inputs to work (so the user can input the character to search for and the string to search in within the same window), but found some help online.

Here's the program in action:



------------------------------------------------------------------------------------------------



------------------------------------------------------------------------------------------------



------------------------------------------------------------------------------------------------



An interesting anecdote - while testing this program at my house, I tried to input a large document from Wikipedia into the righthand box. While it technically ran correctly, it ended up forcing my computer into Windows 7 Basic Desktop mode, as opposed to Aero Desktop, and didn't go back until I closed the program. So that's weird.

Friday, April 17, 2015

Some findings on basic recursion and data type limits.

Going off of CodingBat's first recursion problem, factorial (which can be found right here), I implemented the recursive method into Eclipse and made a working program out of it.

You can view/download the program by clicking here.

While making this program, I realized some interesting things about doing factorials in Java. The main problem is that, if you only use the int data type, the highest number the program can successfully compute the factorial of is 12. Anything past that is computed either negative, incorrect, or just plain old 0

When I changed everything to long, it became possible to calculate factorials up through 20. Anything past that continues to be calculated incorrectly. For example, inputting 21 causes this to happen:




Just goes to show how huge factorial numbers are!

EDIT: Just added a bit of code that splits numbers into groups of three, like this:


All it took was a little imported function.

Monday, April 13, 2015

String[] topic = {"Arrays", "101"};

This unit was all about arrays, which are simply "lists" of values.

Arrays can consist of integers, strings, booleans, object references, you name it.

There are two main ways to create arrays, like this:

int[] grades = new int[10];

Which would create an empty int array of length 10, or:

String[] veggies = {"Cucumber", "Corn", "Lettuce"};

Which would create a defined String array, length three, consisting of Cucumber, Corn, and Lettuce.

Arrays are indexed starting at 0, meaning that Cucumber is at index 0. You can call a value from an array like this:

return veggies[1];

Which would return "Corn", since the array starts at 0.

You can find the length of an array similarly to a String, but instead of .length(), we remove the parentheses and just use .length:

return veggies.length;

This returns 3.

Going back to that first array I made, an int array called grades of length 10,  I can pass in some values for the empty array.

grades[5] = 99;

Now the fifth index, or sixth value, is 99.

Arrays are often used in for loops, like this:

for (i = 0; i < veggies.length, i++) {  //i will be 0, 1, and 2
  return veggies[i];   //Cycles through array and returns each value
}

or, this:

for (int i : veggies) {  //Same thing as before, but simplified
  return veggies[i];
}

You can also make use of multi-dimensional arrays, which work like matrices - rows and columns. But since this is for the "1 Dimensional Array Merit Badge", I won't go into it much here.

Basically, it lets you create an array that looks like this:

[ 0, 25,  3]
[ 1,  3, 53]
[ 3, 74,  8]

Which has three rows and three columns. Rows are horizontal whereas columns are vertical. To find the index of a particular value, you would use the format (row, column). So, that 74 right there? It would be (2, 1) because it's in row 2 (which is the third row, but remember that the index starts at 0) and column 1 (which is the second column). 

Hooray!

Monday, March 16, 2015

Pig Latin Translator v1.0

Finally got the pig latin translator working properly (mostly). It accounts for special cases like qu, ph, ch, and sh. However, I have not yet implemented the ability to search for vowels past the first two characters. This requires a lot of extra booleans and reformatting my entire code. Here's the current code, nonetheless:

import javax.swing.JOptionPane;

public class NoPleaseStop {

 public static void main(String[] args){
  String user_input = JOptionPane.showInputDialog("Enter a word to 
translate:").toLowerCase();
  String[] vowels = {"a", "e", "i", "o", "u"}; //array of vowels
  String result = ""; //creates empty string for final translation
  boolean check = false; //Used for vowel/consonant rules
  
        if (isAlpha(user_input) == false) { //A little code Brian 
showed me, checks for proper notation
            JOptionPane.showMessageDialog(null, "No extra symbols 
or sentences, please. Just one word.", "USER ERROR", JOptionPane
.INFORMATION_MESSAGE); //Explains user error
        } else if (user_input.startsWith("qu")) { //Here's some 
extra rules
         result = user_input.substring(2) + "quay";
         JOptionPane.showMessageDialog(null, result, "Translation",
 JOptionPane.INFORMATION_MESSAGE); //Prints the translation
        } else if (user_input.startsWith("ph")) {
         result = user_input.substring(2) + "phay";
         JOptionPane.showMessageDialog(null, result, "Translation"
JOptionPane.INFORMATION_MESSAGE); //Prints the translation
        } else if (user_input.startsWith("sh")) {
         result = user_input.substring(2) + "shay";
         JOptionPane.showMessageDialog(null, result, "Translation"
JOptionPane.INFORMATION_MESSAGE); //Prints the translation
        } else if (user_input.startsWith("ch")) {
         result = user_input.substring(2) + "chay";
         JOptionPane.showMessageDialog(null, result, "Translation"
JOptionPane.INFORMATION_MESSAGE); //Prints the translation
        } else {
          for (int i = 0; i < vowels.length; i++) {
           if (user_input.startsWith(vowels[i])) {
            check = true;
           }
          }
          if (check) {
           result = user_input + "yay"; //vowel rule
          } else {
           result = user_input.substring(1) + user_input.charAt(0)
 + "ay"; //consonant rule
          }
          JOptionPane.showMessageDialog(null, result, "Translation",
 JOptionPane.INFORMATION_MESSAGE); //Prints the translation
      }
 }
 
    public static boolean isAlpha(String user_input) {  
//The other bit of the code Brian showed me
        char[] chars = user_input.toCharArray(); 
//It checks for correct characters!
        for (char c : chars) {
            if(!Character.isLetter(c)) {
                return false;
            }
        }
        return true; 
    }
    
}
 
Sorry for the poor formatting, Blogger doesn't like code. Here's some example inputs/outputs:







Wednesday, March 4, 2015

Basic Battleship v1.1

I edited the code of my basic Battleship program to include option panels as opposed to writing directly in the console. The main things that were added were:

import javax.swing.JOptionPane; //Function used to create panel

/*
 * Pretend the rest of the code is here, nothing was changed
 */

String guess = JOptionPane.showInputDialog("Enter your guess here (0-7): ");  
//Creates a window where the user can input their guess

/*
 * Rest of the code goes here
 */

The remaining code from v1.0 was unchanged and worked smoothly. I want to add a window to display whether or not the user's guess is a hit or a miss, but that goes more into JFrames and JPanels and UI that I'm assuming gets covered more in Chapter 6. I just wanted to make sure I understood JOptionPane for this activity.

Monday, March 2, 2015

Tim and Ché's Fantabulous Age-Checker Machine-omatic 2000

We made some code that checks your age and sees if you're 18 or older.

Ché put the code on his blog, you can find it here.

Chapter 5's Basic Battleship Game

This chapter focused on making a Battleship-style game, but only in one dimension. The code in the chapter was left somewhat unfinished - they used a fake "GameHelper" object in place of real user input - but I fixed it and used a Scanner object to detect user input. Here's the code:

import java.util.Scanner;

public class SimpleDotCom {

  int[] locationCells;
 int numOfHits = 0;
 
 public void setLocationCells(int[] locs) {
  locationCells = locs;
 }
 
 public String checkYourself(String stringGuess) {
  int guess = Integer.parseInt(stringGuess);
  String result = "miss";
  
  for (int cell : locationCells) {
   if (guess == cell) {
    result = "hit";
    numOfHits++;
    break;
   }
  }
  
  if (numOfHits == locationCells.length) {
   result = "kill";
  }
  
  System.out.println(result);
   return result;
 }
 
 public static void main(String[] args) {
  int numOfGuesses = 0;
  Scanner user_input = new Scanner(System.in); //Switched "GameHelper" to Scanner function
  
  SimpleDotCom theDotCom = new SimpleDotCom();
  int randomNum = (int) (Math.random() *5);
  
  int[] locations = {randomNum, randomNum+1, randomNum+2};
  theDotCom.setLocationCells(locations);
  boolean isAlive = true;
  
  while(isAlive == true) {
   System.out.println("Enter a number:");
   String guess = user_input.nextLine(); //Used scanner functionality for user input
   String result = theDotCom.checkYourself(guess);
   numOfGuesses++;
   if (result.equals("kill")) {
    isAlive = false;
    System.out.println("You took " + numOfGuesses + " guesses!");
   }
  }
  user_input.close();
 }
}

And here's an example of a game in action:

Enter a number:
5
miss
Enter a number:
4
miss
Enter a number:
7
miss
Enter a number:
8
miss
Enter a number:
6
miss
Enter a number:
1
hit
Enter a number:
2
hit
Enter a number:
3
kill
You took 8 guesses!


Thursday, February 26, 2015

Feb. 26th Warm-Up

Today we had to make a relatively simple program that takes a user input of a full name (first and last) and splits it into first and last name. Here's my code:


Wednesday, February 11, 2015

Head-First Java - Chapter 4 - What I Learned

There was a lot of information in Chapter 4, from parameters and arguments, to return values, to encapsulation, to instance and local variables. Here are a couple things I learned in particular:

  • Using the vocabulary "call" and "pass" refers to using a method within a particular reference object, and inputing a value where applicable ("passing" the value). For example:
    Dog d = new Dog();            //Makes new dog ref obj
    d.bark(3);                    //Tells it to bark 3 times

    void bark(int numOfBarks) {   //Defines bark function
        while (numOfBarks > 0) {  //3 is inserted into numOfBarks
            System.out.println("ruff");
            numOfBarks = numOfBarks - 1; //Bark will repeat
        }
    }
    • In the above example, a new reference object for Dog is created, and the value of 3 is passed in. Now, 3 replaces the "numOfBarks" int, causing the program to run and print out "ruff ruff ruff".
  • Whenever we use the void return type, it causes the particular method we're referring to to not return any values. We can set these methods to return anything, but we have to be sure to declare a specific return value and eventually return the correct value type.
  • Encapsulation is basically just a format used to prevent instant variables from being declared something ridiculous, like a cat's height being zero (theCat.height = 0;). In order to prevent something like this from happening, we just have to "encapsulate" the instance variables with setter methods. "Setters" are just methods that set instance variable values, and "getters" receive them. 
  • So, instead of theCat.height = 0 being possible, we have to create code like this:
    public void setHeight(int ht) {    //Height is set by "ht"
        if (ht > 9) {                  //Code only works if you set the height greater than 9
            height = ht;
        }
    }  
  • By doing this, it forces the input to be larger than 9, so we don't get a case of the Pancake Cat.
  • Lastly, this chapter hit upon the difference between instance and local variables.
    • In short, instance variables are declared within a class but NOT within a method, whereas local variables are specifically declared within a method itself.
    • Instance variables CAN be used without "initializing" them, or giving them a value. Depending on the type, this could output a 0, 0.0, false, or null.  
    • HOWEVER, local variables (declared in a method) can NOT function like this. It will output an error.
    • Local variables NEED values, whereas instance variables DON'T. For example, this code would run perfectly fine....
class compSciGrade {
    private int quarterTwoGrade;
    private int getGrade() {
        return quarterTwoGrade;
    }
}  
public class compSciGradeTestDrive {
    public static void main (String[] args) {
        compSciGrade q2 = new compSciGrade();
        System.out.println("Your Quarter 2 grade in CompSci is " + q2.getGrade() + ".");
    }
}
  • ...because the variable quarterTwoGrade is declared within a class but not a method, making it an instance variable. Since it is not given a value, the program will automatically assign it the value of 0, and the output would read "Your Quarter 2 grade in CompSci is 0." That's not passing, but at least it's not an error!
    • If the instance variable was moved into the method getGrade(), it wouldn't run properly. I guess you would be passing something - an error!


  

Friday, January 30, 2015

Java Game - Cat Simulator 2015

In order to demonstrate the abilities we've learned in Java over the course of the first three chapters, Ché and I made a program wherein the user names a cat and tells the program what to do with it. This involves petting, giving, watching, or exiting.

Ché has more information about the program itself on his blogspot post for it, we worked together making it. It can be found here.

Wednesday, January 28, 2015

Head-First Java - Chapter 3 - What I Learned

This chapter was all about variable types and their functions. It helped to distinguish between objects and classes, and showed how the whole "Blah blah1 = new Blah();" thing works in terms of using reference variables to control objects. Some other things I got out of this were:


  • Primitive variables come in eight flavors - four relating to integers, two relating to non-integer real numbers (i.e. with decimal points), one for booleans, and one for characters
    • Booleans (boolean), like always, are either True or False
    • Characters (char), can take up 16 bits and assign variables to letters
    • The four integer variables are byte, short, int, and long. They can hold 8 bits, 16 bits, 32 bits, and 64 bits, respectively. They're all used for numerical values, but each are used depending on the size of the value
      • An important thing to note is that a good analogy for these numeric variables are different sized cups. You can redefine smaller values that fit into smaller types as bigger types, like how you can pour something from a small cup into a larger cup. However, you cannot redefine values in bigger types as smaller types, even if they'd technically fit in the bit-constraint. The JVM doesn't want to pour stuff from a big cup into a smaller cup, because it doesn't know if it'd fit or not and prefers to err on the side of caution.
    • Numbers with decimal points (floats, non-integer numbers) have two primitive variable types - floats, which can hold 32 bits, and doubles, which can hold 64 bits. I have no clue why they call the larger version of the float a double - it seems like a pretty unspecific choice of diction for such a particular data type
  • Variables have to start with a letter, underscore, or a dollar sign
    • This helped explain to me why I oftentimes see the $ symbol in Java code
    • Numbers can only be used after the first character in a variable name
  • There are also certain names that cannot be used for a variable, because they are used elsewhere in Java (e.g. class, finally, assert, etc.)
  • Object reference variables are basically remote controls
    • Imagine a line of code that reads "Dog d = new Dog();". This creates a Dog object reference variable, referencing a dog object. This variable holds a sort of remote control called "d", which controls a Dog() object
    • The next line could read "d.bark();", which tells the remote to hit the "bark" button, or call the bark() function on the specific Dog() object that the reference variable is referring to
  • The bit depth of object reference variables aren't relevant
  • As long as a reference variable is assigned to a particular object, that object stays active. If an object remains inactive, it is sent into the "garbage heap" and is no longer reference-able or usable
  • An array variable creates a sort of "tray of cups", with each cup being a variable that holds a particular value

Here's some dog code:


class Dog {
    String name;
    public static void main (String[] args) {
        //make a Dog object and access it
        Dog dog1 = new Dog();
        dog1.bark();
        dog1.name = "Bart";

        //now make a Dog array
        Dog[] myDogs = new Dog[3];
        //and put some dogs in it
        myDogs[0] = new Dog();
        myDogs[1] = new Dog();
        myDogs[2] = dog1;

        //now access the Dogs using the array references
        myDogs[0].name = "Fred";
        myDogs[1].name = "Marge";

        //Hmmm... what is myDog[2] name?
        System.out.print("last dog's name is ");
        System.out.println("myDogs[2].name);

        //new loop through the array, and tell all dogs to bark
        int x = 0;
        while(x < myDogs.length) {
            myDogs[x].bark();
            x = x + 1;
        }
    }

    public void bark() {
        System.out.println(name + " says Ruff!");
    }

    public void cat();
    public void chaseCat();
}
 

Tuesday, January 20, 2015

Head-First Java - Chapter 2 - What I Learned

This chapter helped me understand the basics of Object Oriented Programming (OOP). I really like the concept of OOP, it turns programming from a laundry list of disjointed code to an organized set of classes and objects that can be changed or added to very easily. It makes more sense in relation to the real world.

Some other things I learned include:
  • main() should only be used to test real classes and/or to launch and start a Java application
  • Objects can "talk" to teach other by calling methods on each other
  • "Global" variables don't really exist in Java OOP, but later we'll learn how using public and static can make a variable behave like a global one
  • A class is like a recipe, whereas objects are like cookies
  • Subclasses can inherit instance variables and methods from superclasses 
 There was no actual code to run in this chapter - it was mostly conceptual.

Tuesday, January 13, 2015

Head-First Java - Chapter 1 - What I Learned

  • The main thing I learned was how the syntax of Java differs from Python, like how:
    • All lines end in semicolons, like how most sentences end in periods or other forms of punctuation
    • Functions and loops are "boxed in" with curly braces, to differentiate the code within them that loops and the code outside of them that runs independently from it
    • White space generally doesn't matter, but can be used to organize the program and help aid in the readability of it
    • Object-oriented programming basically just means chopping up a big, procedural program into seperate classes and methods that would make sense in real life (e.g. class Animal, object Dog)
    • I used to get scared of Java because of the dreaded "public static void main (String[] args)" line, because I never had any clue what it meant. But now I understand that public makes the code, well public, void means there's no return value, and main is just the name of the current method, which is a group of code within a class
    • Most concepts from Scratch and Python, like how integers, strings, Booleans, expressions, loops, etc. work, are nearly the same in Java, but with subtle differences in syntax (e.g. String has to be capitalized when declaring a string variable in Java)

  • I made a separate post about the "99 Bottles of Beer on the Wall" problem, which can be found here.

  • I also made the "PhraseOMatic" program, according to how the chapter did it (code below). I was able to work my way through what was happening while I wrote it, and confirmed my beliefs on the following page, which explained the code:
    • The code creates three lists of words
    • Sets the length of each list, in terms of how many words there are in each one, to a variable
    • Generates a random number within the length of each list, creates a variable for each list with this number (the random function uses a value between 0 and 1, multiplies the length by it, and rounds the float to an integer, in essence creating a random number)
    • Creates a string that combines the three different random values for each list, pulling out a word from each list and concatenating them together
    • Finally, this concatenation is combined with a final string that puts the three words into a proper sentence, and prints that string
public class PhraseOMatic {
  public static void main (String[] args) {   

    String[] wordListOne = {"24/7", "multi-Tier", "30,000 foot", "B-to-B", "win-win", "front-end", "web-based", "pervasive", "smart", "six-sigma", "critical-path", "dynamic"};

    String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented", "centric", "distributed", "clustered", "branded", "outside-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"};

    String[] wordListThree = {"process", "tipping-point", "solution", "architecture", "core competency", "strategy", "mindshare","portal", "space", "vision", "paradigm", "mission"};

int oneLength = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.legth;

int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);

String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];

System.out.println("What we need is a " + phrase); 

  }

Friday, January 9, 2015

Java - 99 Bottles of Beer on the Wall *FIX*

In the Heads-On Java activity "Coding a Serious Business Application", it showed us a finished program that runs through the song "99 Bottles of Beer on the Wall", but with a small problem that we needed to find and fix. 

The problem ended up being an if statement put before the rest of the content within the while loop, that needed to be integrated farther down. The if statement regarded beerNum equaling 1, changing the word from "bottles" to "bottle" so it made sense with a quantity of 1. It was originally before the "beerNum = beerNum - 1" statement, which decreases the amount of bottles. It needed to be after it, so the program can check for the bottle equaling 1 before it says the next phrase. I commented where the if statement used to be, and highlighted where I put it to fix the program.

public class BeerSong {

    public static void main(String[] args) {

        int beerNum = 99;
        String word = "bottles";
        
        while (beerNum > 0) {

            //This is where the if statment used to be
            
            System.out.println(beerNum + " " + word + " of beer on the wall");
            System.out.println(beerNum + " " + word + " of beer.");
            System.out.println("Take one down.");
            System.out.println("Pass it around.");
            beerNum = beerNum - 1;
            
            if (beerNum == 1) {
                word = "bottle";
            }            
            
            if (beerNum > 0) {
                System.out.println(beerNum + " " + word + " of beer on the wall");
            } else {
                System.out.println("No more bottles of beer on the wall");
            }
        }
    }  
}