Java Hello Hacks

// Define Static Method within a Class
public class HelloStatic {
    // Java standard runtime entry point
    public static void main(String[] args) {    
        System.out.println("Hello World!");
    }
}
// A method call allows us to execute code that is wrapped in Class
HelloStatic.main(null);   // Class prefix allows reference of Static Method
Hello World!
// Define Class with Constructor returning Object
public class HelloObject {
    private String hello;   // instance attribute or variable
    public HelloObject() {  // constructor
        hello = "Hello, World!";
    }
    public String getHello() {  // getter, returns value from inside the object
        return this.hello;  // return String from object
    }
    public static void main(String[] args) {    
        HelloObject ho = new HelloObject(); // Instance of Class (ho) is an Object via "new HelloObject()"
        System.out.println(ho.getHello()); // Object allows reference to public methods and data
    }
}
// IJava activation
HelloObject.main(null);
Hello, World!
// Define Class
public class HelloDynamic { // name the first letter of class as capitalized, note camel case
    // instance variable have access modifier (private is most common), data type, and name
    private String hello;
    // constructor signature 1, public and zero arguments, constructors do not have return type
    public HelloDynamic() {  // 0 argument constructor
        this.setHello("Hello, World!");  // using setter with static string
    }
    // constructor signature, public and one argument
    public HelloDynamic(String hello) { // 1 argument constructor
        this.setHello(hello);   // using setter with local variable passed into constructor
    }
    // setter/mutator, setter have void return type and a parameter
    public void setHello(String hello) { // setter
        this.hello = hello;     // instance variable on the left, local variable on the right
    }
    // getter/accessor, getter used to return private instance variable (encapsulated), return type is String
    public String getHello() {  // getter
        return this.hello;
    }
    // public static void main(String[] args) is signature for main/drivers/tester method
    // a driver/tester method is singular or called a class method, it is never part of an object
    public static void main(String[] args) {  
        HelloDynamic hd1 = new HelloDynamic(); // no argument constructor
        HelloDynamic hd2 = new HelloDynamic("Hello, Nighthawk Coding Society!"); // one argument constructor
        System.out.println(hd1.getHello()); // accessing getter
        System.out.println(hd2.getHello()); 
    }
}
// IJava activation
HelloDynamic.main(null);
Hello, World!
Hello, Nighthawk Coding Society!

Java Console Hacks

public class Work{
    // Private object variables 
    private String name;
    private int exp;
    private int yearsincomp;
    private String email;


    // Constructor for the database 
    public Work(String name, int exp, int yearsincomp, String email){
        this.name = name;
        this.exp = exp;
        this.yearsincomp = yearsincomp;
        this.email = email;
    }
    
    // Getter method for the name
    public String getName() {
        return name;
    }

    // Setter method for the name
    public void setName(String name) {
        this.name = name;
    }

    public int getExperience() {
        return exp;
    }

    public void setExperience(int exp) {
        this.exp = exp;
    }

    public int getYearsInCompany() {
        return yearsincomp;
    }

    public void setYearsInCompany(int yearsincomp) {
        this.yearsincomp = yearsincomp;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    // Tester method/data
    public static Work[] makeWork() {
        Work[] worker = new Work[3];
        worker[0] = new Work("Mr.Mortensen", 20, 10, "mort@gmail.com");
        worker[1] = new Work("Jishnu", 2, 0, "jish@gmail.com");
        worker[2] = new Work("Lebron", 2, 0, "dre@gmail.com");
        
        return worker;
    }

    // main method
    public static void main(String[] args) {
        // Create an array of Work objects
        Work[] workers = makeWork();

        // Print information about the workers
        for (Work worker : workers) {
            System.out.println("Name: " + worker.getName());
            System.out.println("Experience: " + worker.getExperience() + " years");
            System.out.println("Years in Company: " + worker.getYearsInCompany() + " years");
            System.out.println("Email: " + worker.getEmail());
            System.out.println();
        }
    }
}

Work.main(null)
Name: Mr.Mortensen
Experience: 20 years
Years in Company: 10 years
Email: mort@gmail.com

Name: Jishnu
Experience: 2 years
Years in Company: 0 years
Email: jish@gmail.com

Name: Lebron
Experience: 2 years
Years in Company: 0 years
Email: dre@gmail.com

Reorganization is important because it enables for us to look at maybe something specific and check if it is working or not without needing to search through a whole code segment in order to find or change something. AP identification allows for us to build connection to the stuff we are doing and even understand why we are doing something in class.

Higher/Lower

Changes made:

  • Made it into a class
import java.util.Scanner;

public class HorlGame {
    public void play() {
        System.out.println("Higher or Lower");
        System.out.println("You have three guesses to guess the number I am thinking of between 1-8.");
        System.out.println("If you guess the number correctly, you win!");
        Scanner scHL = new Scanner(System.in);
        int randomG = (int) (Math.random() * 8) + 1;

        for (int i = 3; i > 0; i--) {
            int guess = scHL.nextInt();

            if (guess == randomG) {
                System.out.println("You win!");
                break;
            } else if (guess > randomG) {
                System.out.println("The number is lower");
            } else if (guess < randomG) {
                System.out.println("The number is higher");
            }
        }

        System.out.println("Game over.");
        scHL.close();
    }
}

Rock Paper and Scissors

Changes made:

  • Made this into a class
import java.util.Random;
import java.util.Scanner;

public class RockPaperScissorsGame {
    private Scanner scanner;
    
    public RockPaperScissorsGame() {
        scanner = new Scanner(System.in);
    }
    
    public void play() {
        System.out.println("Rock Paper Scissors");
        System.out.println("Type 'r' for rock, 'p' for paper, or 's' for scissors");
        
        String userChoice = getUserChoice();
        String computerChoice = generateComputerChoice();
        
        determineWinner(userChoice, computerChoice);
        
        scanner.close();
    }
    
    private String getUserChoice() {
        String userChoice = scanner.nextLine().toLowerCase();
        while (!isValidChoice(userChoice)) {
            System.out.println("Invalid input, try again");
            userChoice = scanner.nextLine().toLowerCase();
        }
        return userChoice;
    }
    
    private boolean isValidChoice(String choice) {
        return choice.equals("r") || choice.equals("p") || choice.equals("s");
    }
    
    private String generateComputerChoice() {
        int random = (int) (Math.random() * 3);
        switch (random) {
            case 0:
                return "r"; // Rock
            case 1:
                return "p"; // Paper
            default:
                return "s"; // Scissors
        }
    }
    
    private void determineWinner(String userChoice, String computerChoice) {
        System.out.println("You chose " + translateChoice(userChoice));
        System.out.println("The computer chose " + translateChoice(computerChoice));
        
        if (userChoice.equals(computerChoice)) {
            System.out.println("It's a tie!");
        } else if (
            (userChoice.equals("r") && computerChoice.equals("s")) ||
            (userChoice.equals("p") && computerChoice.equals("r")) ||
            (userChoice.equals("s") && computerChoice.equals("p"))
        ) {
            System.out.println("You win!");
        } else {
            System.out.println("You lose!");
        }
    }
    
    private String translateChoice(String choice) {
        switch (choice) {
            case "r":
                return "rock";
            case "p":
                return "paper";
            default:
                return "scissors";
        }
    }
}

Tic Tac Toe

Changes made:

  • Previously code was using else and else if repeatedly instead, I used an array and compare the current board to the that array
  • Made player 2 run the same procedure for a move as player 1
  • Deleted the original computer moves and kept it as random but made it run a similar procedure as the a normal player
import java.util.Random;
import java.util.Scanner;

public class TicTacToeGame {
    String[] board;
    String currentPlayer;
    boolean againstComputer;
    int turn;

    public TicTacToeGame() {
        board = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9"}; // we create the board using an array
        currentPlayer = "X";
        againstComputer = false;
        turn = 0;
    }

    void play() {
        System.out.println("Tic Tac Toe");
        Scanner scanner = new Scanner(System.in);

        System.out.println("Do you want to play against a friend or the computer?");
        System.out.println("Type 1 for friend, 2 for computer");
        int choice = scanner.nextInt();

        if (choice == 2) {
            againstComputer = true;
        }

        while (true) {
            printBoard();

            if (turn == 9 || checkWin()) { // If this move was the 9th move check the win conditions and end loop
                printResult();
                break;
            }

            if (againstComputer && currentPlayer.equals("0")) {
                ComputerMove();
            } else {
                PlayerMove(scanner); // Move is made by player
            }

            turn++;
            currentPlayer = (currentPlayer.equals("X")) ? "O" : "X"; // if current player is X change it to 0 else if current player is 0, change it to X
        }

        scanner.close();
    }

    void printBoard() {
        for (int i = 0; i < 9; i += 3) { // we set the range of variables and break it into 3 rows
            System.out.println(board[i] + " | " + board[i + 1] + " | " + board[i + 2]);
        }
    } 

    void PlayerMove(Scanner scanner) {
        int move;
        do {
            System.out.println("Player " + currentPlayer + "'s turn");
            System.out.println("Type the number of the square you want to place your piece in");
            move = scanner.nextInt();
        } while (move < 1 || move > 9 || !board[move - 1].equals(Integer.toString(move))); //  while loop that runs until valid input 

        board[move - 1] = currentPlayer;
    }

    void ComputerMove() {
        Random Cdecision = new Random();
        int move;
        do {
            move = random.nextInt(9) + 1;
        } while (!board[move - 1].equals(Integer.toString(move)));

        System.out.println("Computer's move: O");
        board[move - 1] = currentPlayer;
    }

    boolean checkWin() {
        return (board[0].equals(board[1]) && board[1].equals(board[2])) || // Checks the Rows
                (board[3].equals(board[4]) && board[4].equals(board[5])) ||
                (board[6].equals(board[7]) && board[7].equals(board[8])) ||
                (board[0].equals(board[3]) && board[3].equals(board[6])) || // Checks the Columns
                (board[1].equals(board[4]) && board[4].equals(board[7])) ||
                (board[2].equals(board[5]) && board[5].equals(board[8])) ||
                (board[0].equals(board[4]) && board[4].equals(board[8])) || // Checks the Diagonals
                (board[2].equals(board[4]) && board[4].equals(board[6]));
    }

    void printResult() {
        printBoard();
        if (checkWin()) {
            System.out.println("Player " + currentPlayer + " wins!");
        } else {
            System.out.println("It's a tie!");
        }
    }
}
public class ConsoleGame {
    public final String DEFAULT = "\u001B[0m";  // Default Terminal Color
    
    public ConsoleGame() {
        startGame();
    }

    public void startGame() {
        Scanner sc = new Scanner(System.in);  // using Java Scanner Object
        
        boolean quit = false;
        while (!quit) {
            menuString();  // print Menu
            try {
                int choice = sc.nextInt();  // using method from Java Scanner Object
                System.out.print("" + choice + ": ");
                quit = action(choice);  // take action
            } catch (Exception e) {
                sc.nextLine(); // error: clear buffer
                System.out.println(e + ": Not a number, try again.");
            }
        }
        sc.close();
    }

    public void menuString(){
        String menuText = ""
                + "\u001B[35m___________________________\n"  
                + "|~~~~~~~~~~~~~~~~~~~~~~~~~|\n"
                + "|\u001B[0m          Menu!          \u001B[35m|\n"
                + "|~~~~~~~~~~~~~~~~~~~~~~~~~|\n"
                + "| 0 - Exit                |\n"    
                + "| 1 - Rock Paper Scissors |\n"
                + "| 2 - Higher or Lower     |\n"
                + "| 3 - Tic Tac Toe         |\n"
                + "|_________________________|   \u001B[0m\n"
                + "\n"
                + "Choose an option.\n"
                ;
        System.out.println(menuText);
    }

    private boolean action(int selection) {
        boolean quit = false;
        switch (selection) {  // Switch or Switch/Case is Control Flow statement and is used to evaluate the user selection
            case 0:
                System.out.print("Goodbye, World!"); 
                quit = true; 
                break;
            case 1:
                RockPaperScissorsGame rpsGame = new RockPaperScissorsGame();
                rpsGame.play();
                break;
            case 2:
                HorlGame horlGame = new HorlGame();
                horlGame.play();
                break;
            case 3:
                TicTacToeGame TTTGame = new TicTacToeGame();
                TTTGame.play();
                break;
            default:
                //Prints error message from console
                System.out.print("Unexpected choice, try again.");
        }
        System.out.println(DEFAULT);  // make sure to reset color and provide a new line
        return quit;
    }

    public static void main(String[] args) {
        ConsoleGame game = new ConsoleGame();
        game.startGame();
    }
}

Key Takeaways / Things I learnt

  • Some important things that I learnt is that static makes it so that you cant modify the values in something
  • I also learned about the different operators and how they are in Java, example:   is or, && is and, ? is if its true it returns true, if its false, it’ll return false
  • I also learnt the different things in Java such as void. Void is used as a way to run code and discard its result
  • Public can be accessed by any class or package but private hides it from external code