Tuesday, May 5, 2015

2.2.2.A Conclusion


  1. Well this time it actually changes wiht what you type and it is faster.
  2. Php
  3. Javascript
  4. CSS
  5. It allowed me to start to learn php, and answer the questions.

Monday, April 13, 2015

Arrays

Arrays hold a predefined amount of elements of a predefined type. They're length cannot be changed. You can however change the values of the individual elements. To access the individual elements you have to use indexes. An arrays indexes start at 0 and go to 1 less than the length. So an int array that has a length of 5 has indexes from 0-4. It may be helpfull to iterate through all the elements in an array. You can do this with for loops and the array length.

To define an array you type: x[] y = new x[z]; where x is the type, y is the name, and z is the length.

To find the length you type: y.length; where y is the name.

To access the elements you type: y[z]; where y is the name and z is the index.

To iterate through an array type: for (int i = 0; i < y.length; i++) {} where y is the array.

Tuesday, March 10, 2015

Head First Java Chapter 6

    In this chapter we learned more about the java api in order to fix our old battle ship game. We used the api to get arraylist which i have already been using and know about. They are a lot better than arrays because I find them easier to use and more versatile (They are slower though). I also learned about import packages from the java api. You can browse the internet to see all the classes in it. You have to know the full location or name of the file. You can also import as static which was not discussed but allows makes it so you don't have to type the name of the class to run a method or access a variable. Boolean operators were also explained like and (&&) and or (||), the equals(==) and not equals(!=), and the non short circuit and(&) and or(|).

    This is the code for the battle ship game created in this chapter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.ArrayList;

public class DotCom {
	private ArrayList<String> locationCells;
	private String name;

	public void setLocationCells(ArrayList<String> loc) {
		locationCells = loc;
	}

	public void setName(String n) { //setter
		name = n;
	}

	public String checkYourself(String userInput) {
		String result = "miss";
		int index = locationCells.indexOf(userInput);
		if (index >= 0) {
			locationCells.remove(index);

			if (locationCells.isEmpty()) {
				result = "kill";
				System.out.println("Ouch! You sunk " + name + " : ( ");
			} else {
				result = "hit";
			} // close if
		} // close if
		return result;
	} // close method
} // close class 
 
  

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.ArrayList; 

public class DotComBust {

	private GameHelper helper = new GameHelper();
	private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
	private int numOfGuesses = 0;

	private void setUpGame() {
	 // first make some dot coms and give them locations
		 DotCom one = new DotCom();
		 one.setName("Pets.com");
		 DotCom two = new DotCom();
		 two.setName("eToys.com");
		 DotCom three = new DotCom();
		 three.setName("Go2.com");
		 dotComsList.add(one);
		 dotComsList.add(two);
		 dotComsList.add(three);
		 System.out.println("Your goal is to sink three dot coms.");
		 System.out.println("Pets.com, eToys.com, Go2.com");
		 System.out.println("Try to sink them all in the fewest number of guesses");

		 for (DotCom dotComToSet : dotComsList) {
			 ArrayList<String> newLocation = helper.placeDotCom(3);
			 dotComToSet.setLocationCells(newLocation);
		 } // close for loop
	 } // close setUpGame method

	private void startPlaying() {
		 while(!dotComsList.isEmpty()) {
			 String userGuess = helper.getUserInput("Enter a guess");
			 checkUserGuess(userGuess);
		 } // close while
		 finishGame();
	 } // close startPlaying method

	private void checkUserGuess(String userGuess) {
		 numOfGuesses++;
		 String result = "miss";
		 
		 for (DotCom dotComToTest : dotComsList) {
			 result = dotComToTest.checkYourself(userGuess);
			 if (result.equals("hit")) {
				 break;
			 }
			 if (result.equals("kill")) {
				 dotComsList.remove(dotComToTest);
				 break;
			 }
		 } // close for
		 System.out.println(result);
	 } // close method

	private void finishGame() {
		 System.out.println("All Dot Coms are dead! Your stock is now worthless.");
		 if (numOfGuesses <= 18) {
			 System.out.println("It only took you " + numOfGuesses + " guesses.");
			 System.out.println(" You got out before your options sank.");
		 } else {
			 System.out.println("Took you long enough. "+ numOfGuesses + " guesses.");
			 System.out.println("Fish are dancing with your options.");
		 }
	 } // close method

	public static void main(String[] args) {
		DotComBust game = new DotComBust();
		game.setUpGame();
		game.startPlaying();
	} // close method

}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.*;
import java.util.*;

public class GameHelper {
	private static final String alphabet = "abcdefg";
	private int gridLength = 7;
	private int gridSize = 49;
	private int[] grid = new int[gridSize];
	private int comCount = 0;

	public String getUserInput(String prompt) {
		String inputLine = null;
		System.out.print(prompt + " ");
		try {
			BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
			inputLine = is.readLine();
			if (inputLine.length() == 0) return null;
		} catch (IOException e) {
			System.out.println("IOException: " + e);
		}
		return inputLine.toLowerCase();
	}

	public ArrayList<String> placeDotCom(int comSize) {
		ArrayList<String> alphaCells = new ArrayList<String>();
		String[] alphacoords = new String[comSize]; // holds ‘f6’ type coords
		String temp = null; // temporary String for concat
		int[] coords = new int[comSize]; // current candidate coords
		int attempts = 0; // current attempts counter
		boolean success = false; // flag = found a good location ?
		int location = 0; // current starting location

		comCount++; // nth dot com to place
		int incr = 1; // set horizontal increment
		if ((comCount % 2) == 1) { // if odd dot com (place vertically)
			incr = gridLength; // set vertical increment
		}
		while (!success & attempts++ < 200) { // main search loop (32)
			location = (int) (Math.random() * gridSize); // get random starting point
			//System.out.print(“ try “ + location);
			int x = 0; // nth position in dotcom to place
			success = true; // assume success
			while (success && x < comSize) { // look for adjacent unused spots
				if (grid[location] == 0) { // if not already used
					coords[x++] = location; // save location
					location += incr; // try ‘next’ adjacent
					if (location >= gridSize) { // out of bounds - ‘bottom’
						success = false; // failure
					}
					if (x > 0 && (location % gridLength == 0)) { // out of bounds - right edge
						success = false; // failure
					}
				} else { // found already used location
					// System.out.print(“ used “ + location);
					success = false; // failure
				}
			}
		} // end while

		int x = 0; // turn location into alpha coords
		int row = 0;
		int column = 0;
		// System.out.println(“\n”);
		while (x < comSize) {
			grid[coords[x]] = 1; // mark master grid pts. as ‘used’
			row = (int) (coords[x] / gridLength); // get row value
			column = coords[x] % gridLength; // get numeric column value
			temp = String.valueOf(alphabet.charAt(column)); // convert to alpha

			alphaCells.add(temp.concat(Integer.toString(row)));
			x++;
			// System.out.print(“ coord “+x+” = “ + alphaCells.get(x-1));
		}

		// System.out.println(“\n”);

		return alphaCells;
	}
}

Monday, March 9, 2015

Age Verifier

    I created a program to check if someone is over 18. I only used the main method just because this is a simple program and it went faster.

    The first 6 lines import the necessary files for creating an OptionPane and getting the date.

    From line 9 to 34 i am initializing variables for the current date and the entered date. Specifically, lines 27 to 29 are used to create the panes that get the users input.

    The rest of the code from line 35 on is checking the input with the current time to decide whether the person is 18. Depending on whether they are or aren't it will print in the console and in a pane if they are 18 or not.

    Currently there is nothing to handle if the person inputs a string, or the wrong format or if they click cancel. I am fairly new to JOptionPanes and don't know how to handle the cancel button. With the wrong input I could have handled it by using some if statements on the input.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JOptionPane;

public class Main {

 public static void main(String[] args) {

  String month, day, year;
  int imonth, iday, iyear, itmonth, itday, ityear;
  Date date = new Date();

  DateFormat monthf = new SimpleDateFormat("MM");
  DateFormat dayf = new SimpleDateFormat("dd");
  DateFormat yearf = new SimpleDateFormat("yyyy");

  String todaym = monthf.format(date);
  String todayd = dayf.format(date);
  String todayy = yearf.format(date);

  itmonth = Integer.parseInt(todaym);
  itday = Integer.parseInt(todayd);
  ityear = Integer.parseInt(todayy);

  month = JOptionPane.showInputDialog("Month of birth(MM)");
  day = JOptionPane.showInputDialog("Day of birth(DD)");
  year = JOptionPane.showInputDialog("Year of birth(YYYY)");

  imonth = Integer.parseInt(month);
  iday = Integer.parseInt(day);
  iyear = Integer.parseInt(year);

  if (iyear - ityear == -18) {
   if (imonth - itmonth == 0) {
    if (iday - itday <= 0) {
     System.out.println("you are 18");
     JOptionPane.showMessageDialog(null, "you are 18");
    } else if (iday - itday > 0) {
     System.out.println("you are not 18");
     JOptionPane.showMessageDialog(null, "you are not 18");
    }
   } else if (imonth - itmonth < 0) {
    System.out.println("you are 18");
    JOptionPane.showMessageDialog(null, "you are 18");
   } else if (imonth - itmonth > 0) {
    System.out.println("you are not 18");
    JOptionPane.showMessageDialog(null, "you are not 18");
   }
  } else if (iyear - ityear > -18) {
   System.out.println("you are not 18");
   JOptionPane.showMessageDialog(null, "you are not 18");
  } else if (iyear - ityear < -18) {
   System.out.println("you are 18");
   JOptionPane.showMessageDialog(null, "you are 18");
  }
 }
}

Wednesday, March 4, 2015

Head First Java Chapter 5

    In this chapter I learned about casting primitive variables, and using loops and I created a simple 1D game of battleship.

Casting Primitives:
  You can change one type of variable to another by casting it or using the parse command. You cast a variable by typing (TypeOfVariable). Sometimes this isn't possible like when going from a string to an integer so you can use Integer.parseInt().

Using Loops:
  When trying to do something over and over again you can use loops. There are multiple ways to use them. One is by doing this:
for (String name : nameArray) {}   This code is sets name to an element in the array each time
or
for (int i = 0; i < 20; i++) {} This code sets i to a number from 0 to 19  and then iterates that amount of times.

Battleship:
  This is the code that was used in this chapter to create a program like battleship that only uses a 1D array. I added some comments. 

GameHelper gets the users input:











SimpleDotCom contains the list of ships and the code for if you hit or not:



SimpleDotComTestDrive is the class with the main method, it utilizes the other two in order to run the whole thing:


Monday, February 9, 2015

Head First Java Chapter 4

    In this chapter I learned more about methods in a class. I learned about using private to hide variables so they don't get values I don't want them to have. If they are private you can still change and view them using getters and setters. I learned that all methods need a return type whether it be void or an actual type. I learned methods can have parameters so you can pass values into it.

Private:





Getters and Setters:







Return Type & Parameters:











Dog Code:

This is the code from chapter 4. I added comments explaining what everything does and had to move the test drive class into a new class file to run it in eclipse. This code uses getters and setters, private varibles, and return types. It makes 2 dogs and makes them bark. The type of bark depends on their size.



Thursday, February 5, 2015

Java Palindrome checker

I created a program the accepts a string and checks if it is a palindrome. It is not case sensitive but it will not work with sentences Unless you do not include the spaces between words. There are two classes the main chapter 3 class and the checker class. The checker class checks if it is a palindrome and if it is it prints a line saying that and if not it doesn't. the chapter 3 class get input and sends it to the checker class.


Chapter 3 Class:


Checker Class:



Thursday, January 22, 2015

Head First Java Chapter 3


    In this chapter I learned about primitive and reference variables. Primitive variables values are the bits representing the value. While a reference variable value is the bits representing a way to get to an object on the heap. A reference variable is null when not assigned an object. I learned about creating an array of variables and how it is always an object. I copied this code for a dog program. However, I moved the main method into its own class and put the dog class in a new file. I changed the second line to clarify what the dogs name on the last line was and fixed some grammar.

Dog Program:

Main File:

























Dog File:

















Output:

Thursday, January 15, 2015

Head First Java Chapter 2

    In this chapter I learned about the advantages of object oriented (OO) programing and what exactly it is. This chapter was sort of dull when it came to information about coding, but it had a lot of info on object oriented programs. Object oriented programing is different from procedural programing because with object oriented you think of the things in the program and in procedural you think of the things the program has to do. The main advantage OO has over procedural is that you don't have to edit existing code to add features or things. On the other hand procedural is usually faster to make. I also learned about how a class and a object can inherit methods and instance variables from a superclass or a class respectively.

Tuesday, January 13, 2015

Head First Java Chapter 1

    I read through chapter 1 and did the activities. In this chapter I learned the basics of java. I had no idea that in order to put an else with an if statement you must put it on the same line after the ending '}'.
Like This: 

if (x == 5) {
System.out.println("X = 5");
} else {
System.out.println("X != 5"):
}

    I also learned that empty space doesn't matter and every statement must end in a semi-colon. I leaened the basic structure of a java program which is class-method-statement.

x == 5 or x     ==     5
System.out.println("hi");

    I thought this was the mistake in the Beer program. I had to look back through the chapter to see this. I also learned the basic structure of a java program. The class is used to hold methods, which hold statements. You need a main method in order to start your program. 

    I fixed the Beer program by changing the if statement at the end and adding two if's inside the else. The problem was that one line printed "1 bottles of beer on the wall" which is not proper English. This was partially dealt with towards the beginning of the original program.

package javaapplication1;

public class BeerSong {

    public static void main(String[] args) {
        int beerNum = 99;
        String word = "bottles";
        
        while (beerNum > 0) {
            if (beerNum == 1) {
                word = "bottle"; //Changes bottles to singular if only 1.
            }
            
            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) { //Had to change to 1 to not print '1 bottles of beer...'
                System.out.println(beerNum + " " + word + " of beer on the wall");
            } else {
                if (beerNum == 1) { //Added to make bottles singular when only 1.
                    System.out.println("1 bottle of beer on the wall");
                }
                if (beerNum == 0) { //Moved from original location to this if statement.
                    System.out.println("No more bottles of beer on the wall");
                }
            }
        }
    }

}

Tuesday, December 16, 2014

1.3.8 Conclusion Questions
1. Q: If you change between 1 and 20 from the previous program to between 1 and 6000, how many guesses will you need to guarantee that you have the right answer? Explain.

2. Q: Describe the difference between a while loop and a for loop.


1. A: 13 times because 2^13 > 6000.

2. A: The difference between a while loob and a for loop is that a while loop loops until a condition changes. A for loop iterates through a variable or some sort of item.

1.3.8 Code File
from __future__ import print_function
import random

def goguess():
    # Initialises variables and sets the random number
    tries = 0
    randnum = random.randint(1,20)
    guess = 0
    while guess != randnum:
    # Sets guess to the integer of the input and checks its relation to the random number.
        guess = int(raw_input('I have a number between 1 and 20 inclusive.\nGuess: '))
        if guess > randnum:
            print(guess, 'is to high.')
            tries += 1
        if guess < randnum:
            tries += 1
            print(guess, 'is to low.')
    else: # Once guess == randnum 
        print('Good job the number was', randnum, 'and it took you', tries, 'tries.')

Friday, December 12, 2014

1.3.7 Conclusion Questions

1. Q: Sometimes code using an iterative loop can be written without a loop, simply repeating the iterated code over and over as separate lines in the program. Explain the disadvantages of developing a program this way.

2. Q: Name a large collection across which you might iterate.

3. Q: What is the relationship between iteration and the analysis of a large set of data?


1. A: The advantages of writing code this way is that you can more easily determine the number times something happens and it doesn't have to be linked to anything else. One disadvantage is that you may have to write the code out a lot of times and your file could become very cluttered.

2. A: A large collection you might iterate across could be a list of numbers or letters like in my hangman and lottery programs.

3. A: Iteration and analysis of a large data set both share to repeating of certain processes until a desired result occurs.



What I Did


    I created the Lottery program really fast and decided to focus mainly on the Hangman game. The lottery game just goes through the winning list and checks if the item is in the guessed list and if it is it add one to the common numbers. The big problem is tthis is that you have to input the two lists when running the function. You cannot just type matches(12345,12345) you have to type matches([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]). I find this annoying and would fix it if i really wanted to improve this function. 

   I made the Hangman game slowly and originally started with working code just as simple as the lottery function.  I decided to make it more complex by asking you to input the words and guesses instead of taking them when running the function. I then had to fix a problem where if there were two or more of the same letter in the program it wouldn't report the second number and you still have to tell it a letter twice. There is still a problem I forgot to mention in the final code regarding some that I keep forgetting about. I will update this post when I remember. I had to make raw_input equal to input because of the version of python i was using at home to work on this.


1.3.7 Hangman Code File

from __future__ import print_function

# Hangman Game By Randy Cole Last modified on 12-12-14
# I am aware the variable atemps is spelled wrong
# Some problem I didn't have time to fix:
# 1. The game doesn't support spaces or special characters as they would be given to you in real hangman.

def hangman_display():
 # initializes most variables
    raw_input = input # needed in my home version of python to use raw_input
    blanks = [] # what the user sees to help the guessing
    word = '' # secret word
    guess = '' # the users guess
    atempts = 8 # the amount of tries left

    word = raw_input('What is the secret word?(no spaces only letters)\n').lower()

    while len(word) < 1 or word.isalpha() != True: # checks formating and asks for reentry if wrong
     word = raw_input('Oops you didnt enter anything or had a space or a nonalphabetic character.\nTry again.').lower()

    newword = list(word) # initializes now to take the value after the wrong input check

    for item in word: # sets the variable that displays blanks
        blanks += '-'

    while atempts > 0:
        print(''.join(blanks)) # shows the blanks to the player
        guess = raw_input('Guess a letter.\nIt has to be letters and 1 character only.\nYou must guess multiple letters twice.').lower() # asks for guess
        if len(guess) > 1: # checks if the user inputted anything
            guess = raw_input('Try again with only one letter(press enter to continue).\n').lower() # asks again
        elif guess.isalpha() != True: # checks if user inputed a number or other character that isn't a letter
            guess = raw_input('Must be only letters(Press enter to continue).\n').lower() # asks again
        elif guess in word: # checks if they guessed a correct letter
            pos = word.find(guess) # finds the letter in the word
            blanks[pos] = guess # sets the user display to include the letter
            newword[pos] = '1' # changes a letter to a number
            word = ''.join(newword)  # changes new word back into a string with the number at the letter guessed
            if word.isnumeric() == True: # check is all letters have been guesssed (the word will only have 1s)
                print('You Win!') #tells user they one and ends game
                break
        else: # you guessed a wrong letter removes one attempt and prints remaining ones
            atempts -= 1
            if atempts > 0:
                print('You have', atempts, ' attempt(s) left.')
    else: # if you run put of attempts
        print('You Lose!')

1.3.7 Lottery Ticket Code File

def matches(ticket, winners):
    common = 0
    for item in winners:
        if item in ticket:
            # adds one to common if a number is shared
            common += 1
    print(common)