Learning Objectives

System class methods print output to the console.

  • String literals
  • Primitive Data Types
  • Declaring variables to different data types
  • Use of arithmetic expressions in a program
  • Data stored in variables
  • Assignment Statements

String Literals

  1. Declare a class: public class "name"
  2. Define where the class begins and ends through curly brackets
  3. Inside the curly brackets (class) you must have methods - at least one
  4. Main methods: public static void main(String[] args)
  5. Another curly bracket to define where the method begins and ends -- indented this time
  6. System.out.println (""); -- lets us output text to our console, must end with a semicolon
public class MyFirstProgram {
    
    public static void main(String[] args) 
    {
        System.out.println("Hello World!");
    }
}

MyFirstProgram.main(null)
Hello World!

Declaring and Initializing Variables

  1. Variables defined within a method are local variables
  2. "Int" can hold any whole number
  3. You need an initial value in order to change it or increment it
  4. No quotation mark around variable because this will output the value stored by variable
public class UsingAVariable{
    public static void main(String[] args)
    {
        int x;
        x = 10;
        x = 5;
        x = x + 1;
        int myFinalScore = 10;

        System.out.println(myFinalScore);
    }
}
UsingAVariable.main(null)
10

8 Primitve Data Types

  • Byte: minimum value of -128 and maximum value of 127 (inclusive). It is useful for saving memory in large arrays
  • Short: Minimum value of -32,768 and maximum value of 32,767. Same purpose as Byte
  • Int: Any integer or whole number
  • Long: Greater range than int
  • Float: floating point numbers that tend to have decimals
  • Double: not good for precise data
  • Boolean: logic that evaluates whether a condition is true or false
  • Char
public class PrimitiveDataTypes
{
    public static void main(String[] args)
    {
        int a = 3;
        double b = 3.0;
        b = 3; // only works for double
        a = (int) 3.999; // casting cuts off everything after the decimal
        System.out.println(a);

        boolean c = true;
        c = false;
        System.out.println(c);
    }
}
PrimitiveDataTypes.main(null)
3
false

Arithmetic Operations

public class Operators 
{
    public static void main(String[] args)
    {
        int x;
        x = 3;

        System.out.println(3+3); 
        System.out.println(3-3);
        System.out.println(3*3);
        System.out.println(3/3);
        
        x = 3*3;
        x = 3 * x;

        System.out.println(4 % 3);

    }
}
Operators.main(null)
6
0
9
1
1

Practice 2013 FRQ 1

Part A

public DownloadInfo getDownloadInfo(String title) { // define the class
    for (DownloadInfo info : downloadList){
    if (info.getTitle().equals(title)){
     return info;
     }
    }
    return null; // method inside the class
    }

Part B

public void updateDownloads(List<String> titles) {
    for (String title : titles) {
    DownloadInfo foundInfo = getDownloadInfo(title); // calls method
    if (foundInfo == null){
    downloadList.add(new DownloadInfo(title)); // makes new object
    }
    else {
    foundInfo.incrementTimesDownloaded();
    }
    }
   }

Homework from Presentation

Hack 1.1

public class Printing {
    public static void main(String[] args){
        System.out.println("Hetvi Trivedi");
        System.out.println("JEHB");
}  
}
Printing.main(null);
Hetvi Trivedi
JEHB

Hack 1.2

public class Biodata {

    public static void main(String[] args) {
        String name = "Hetvi";
        int age = 17;
        boolean underclassman = false;
        double height = 5.3;

        System.out.println(name);
        System.out.println(age);
        System.out.println(underclassman);
        System.out.println(height);
    }
}

Biodata.main(null);
Hetvi
17
false
5.3

Hack 1.3

public class Num {

    public static void main(String[] args) {
    double num = ( ( ( 6 * 1234124 ) / 11345 ) - 890809 + 90800 ) % 980098;
    num = num / 100;
    System.out.println(num);

}
}

Num.main(null);
-7993.57

Hack 1.4

  • Used operators slightly different in a more user friendly way!
import java.util.Scanner; //library for user input
import java.lang.Math; //library for random numbers


public class Menu {
    // Instance Variables
    public final String DEFAULT = "\u001B[0m";  // Default Terminal Color
    public final String[][] COLORS = { // 2D Array of ANSI Terminal Colors
        {"Default",DEFAULT},
        {"Red", "\u001B[31m"}, 
        {"Green", "\u001B[32m"}, 
        {"Yellow", "\u001B[33m"}, 
        {"Blue", "\u001B[34m"}, 
        {"Purple", "\u001B[35m"}, 
        {"Cyan", "\u001B[36m"}, 
        {"White", "\u001B[37m"}, 
    };
    // 2D column location for data
    public final int NAME = 0;
    public final int ANSI = 1;  // ANSI is the "standard" for terminal codes

    // Constructor on this Object takes control of menu events and actions
    public Menu() {
        Scanner sc = new Scanner(System.in);  // using Java Scanner Object
        
        this.print();  // print Menu
        boolean quit = false;
        while (!quit) {
            try {  // scan for Input
                int choice = sc.nextInt();  // using method from Java Scanner Object
                System.out.print("" + choice + ": ");
                quit = this.action(choice);  // take action
            } catch (Exception e) {
                sc.nextLine(); // error: clear buffer
                System.out.println(e + ": Not a number, try again.");
            }
        }
        sc.close();
    }

    // Print the menu options to Terminal
    private void print() {
        //System.out.println commands below is used to present a Menu to the user. 
        System.out.println("-------------------------\n");
        System.out.println("Choose from these choices");
        System.out.println("-------------------------\n");
        System.out.println("1 - Say Hello");
        System.out.println("2 - Output colors");
        System.out.println("3 - Loading in color");
        System.out.println("4 - Greatest Common Factor");
        System.out.println("5 - Least Common Multiple");
        System.out.println("0 - Quit");
        System.out.println("-------------------------\n");
    }

    // Private method to perform action and return true if action is to quit/exit
    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:
                System.out.print("Hello, World!");
                break;
            case 2:
                for(int i = 0; i < COLORS.length; i++)  // loop through COLORS array
                    System.out.print(COLORS[i][ANSI] + COLORS[i][NAME]);
                break;
            case 3:
                System.out.print("Loading...");
                for (int i = 0; i < 20; i++) {  // fixed length loading bar
                    int random = (int) (Math.random() * COLORS.length);  // random logic
                    try {
                        Thread.sleep(100);  // delay for loading
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                    System.out.print(COLORS[random][ANSI] + "#");
                }
                break;

            case 4:
                // two numbers from user input
                Scanner input = new Scanner(System.in);
                System.out.println("Enter a number: ");
                int a = input.nextInt();
                System.out.println("Enter another number: ");
                Scanner input2 = new Scanner(System.in);
                int b = input2.nextInt();
        
                int c = Math.min(a, b);
                input.close();
                input2.close();
                int gcd = 1;
                for(int i = c; i > 0; i--){ // descending
                    if(a % i == 0 && b % i == 0){
                        gcd = i;
                        break; // exit loop if it is a factor
                    }
                }
                System.out.println("The greatest common factor of " + a + " and " + b + " is " + gcd);
                break; 
                
            case 5:
                Scanner num1 = new Scanner(System.in);
                System.out.println("Enter a number: ");
                int x = num1.nextInt();
                Scanner num2 = new Scanner(System.in);
                System.out.println("Enter another number: ");
                int y = num2.nextInt();
        
                num1.close();
                num2.close();
        
                int m = Math.max(x, y); // least common multiple must be at least as large as the larger of the two numbers
        
                while (true) { // repeat until break
                    if(m % x == 0 && m % y == 0){
                        System.out.println("The least common multiple of " + x + " and " + y + " is " + m);
                        break;
                    }
                    m += 1;
                }
                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 new line
        return quit;
    }

    // Static driver/tester method
    static public void main(String[] args)  {  
        new Menu(); // starting Menu object
    }

}
Menu.main(null);
-------------------------

Choose from these choices
-------------------------

1 - Say Hello
2 - Output colors
3 - Loading in color
4 - Greatest Common Factor
5 - Least Common Multiple
0 - Quit
-------------------------

4: Enter a number: 
Enter another number: 
The greatest common factor of 4 and 5 is 1

0: Goodbye, World!

Hack 1.5

public class CastActivity {

    public static void main(String[] args) {
        double dNum = 123456.123456;
        int dInt = (int) dNum;
        System.out.println("the double to the integer is: " + dInt);

    }
}

CastActivity.main(null);
the double to the integer is: 123456