===================
===================

Java AP Programming Assignments

===================
===================

Java Programming Assignments for CS 1 AP

Programming Assignments (more to come)

Unit 0a Labs

Unit 0a Lab 01 ASCII Box 1

Unit 0a Lab 02 ASCII Box 2

Unit 0a Lab 03 ASCII Art


Unit 0b Labs

Unit 0b Lab 01 Variables

Unit 0b Lab 02 All About Me


Unit 0c Labs

Unit 0c Lab 01 Keyboard Input

Unit 0c Lab 02 Slope of a Line




Online Java Compilers

Java repl.it (We will use this one)
Java onlinegdb IDE (backup)
Java IDE JDoodle (backup)

Online Help Sites for Java

JavaHelp Website
w3schools.com Website
Java Tutorials Point tutorials

Videos for Java

Java Video Syntax and Output
Variables and Data Types
Math Operations
Input and Output
YouTube Video

Importance of Programming and a Brief Introduction

Importance of Programming Sample Programs
Sample Program - Keyboard Input
Sample Program - Mod and Div
Sample Program - Methods
Sample Program - Return Methods
Sample Program - Class Student
Sample Program - Class Employee
Sample Program - Class Cat
Sample Program - Class Math
Sample Program - Class Methods
=================================
=================================

Importance of Computers and Intro to Java

=================================
=================================


Importance of Software

Software or computer programs are what makes a computer do stuff. Without software, a computer is nothing but a big paper weight. It takes both hardware and software (computer programs, apps, code, ...). There are millions of lines of computer code (instructions, commands) in a computer, phone, car, automation lines, robots, planes, trains, etc. Software is everywhere!!! Businesses use it to keep track of products, employees, etc. Schools use it to keep track of student information, grades, etc. as well as to keep track of employees, pay, purchasing, etc. Every company uses computers and lots of software to run their operations, including schools, etc. Software is a big mystery to a lot of people! And it has caused a lot of problems in industry, education, etc. I have been told several times that I was fired by assistant principals and company execs because they did not understand software (I luckily never got fired). I read once a few years ago that more companies have gone bankrupt because of poor decisions about software (including a company that I used to work for).

Hardware and Software (Working together)

CPU

This component is responsible for carrying out our instructions (commands). It is called the Central Processing Unit.

RAM Memory

This is very fast memory that is used to store the OS instructions, all program data, and every program's code that is open. The OS is loaded when the computer is first started (turned on). We call this booting the computer. When you open an application, it is loaded (copied) from external storage (hard drive, ssd drive, etc.)into the RAM memory along with the data. When you terminate a program, the program instructions and data are erased from the RAM memory. When you shut down (turn off) your computer, all of the programs and data in RAM memory are gone. It is like turning off a light.

ROM Memory

This memory is what starts your computer system when you turn it on (boot it). It contains the basic start up commands to allow you to set which drive is the bootable drive, the boot order, the start up commands to load the operating system into RAM memory, and more.

Mother Board

This hardware is used to connect the CPU, RAM memory, drives, ports, etc.

External Storage

Hard Drive (ssd drives, flash drives, etc.) These devices permanently hold your programs and data, and if bootable, holds the OS as well.

Software

Computer programs (apps) including the OS.

Operating System (OS) (Windows, Mac OS, Linux, ...)

This is the program that is in total control of the machine. It displays the desktop or command line, and allows you to copy files, delete files, organize files (like in folders, etc.), etc.

What is a computer program? (application)

A computer program is a sequence of instructions (commands, statements) for a computer to follow.

What is a computer programming language?

A computer language contains high level commands to allow you to communicate with the CPU.

Can you name some computer langages?

C, C++, ?????????

Compilers vs. Interpreted languages

Many languages need to be compiled or translated into machine code before you can run (execute) them. (C, C++, Pascal, Java, Swift, etc.) Interpreted languages are converted to machine code as they run. Interpreted languages are generally slightly slower (less efficient) than compiled code. (Python) Think about how you might talk to a French person if you did not speak any French.

What is an IDE?

An IDE is an Integrated Development Environment. It contains an editor for typing in our code (instructions, commands), a button or menu item to compile and run our program, and other utilities. IDLE, JDoodle for Python, Eclipse are examples of some IDE's.

What is an algorithm?

An algorithm is a step by step set of instructions (commands) to someone or some thing to carry out a task.

What does it mean to execute or run a program?

It means to carry out (run, execute) the instructions in your program.

What is a variable?

A variable refers to a place in RAM memory where you can store information (numbers, strings of characters, etc.) Think of a box that holds data. Variables have names so that us humans can refer to them. Variable names should be descriptive of what kind of information they refer to. Names must start with a letter of the alphabet. After that you can have more letters or numbers or the underscore(_) character. However, you can not have a space character or any other special characters in your name. We should always user lower case letters, except on word boundaries for long names. Variables can not be key words of the programming language. (Keywords: byte, short, char, int, long, float, double boolean, if, else, for, while, etc. Also, names are case sensitive. So, X and x are actually different names. Some examples of legal variable names: x y answer b num totalSum answer x y -------- -------- -------- | 12 | | 7 | | 5 | -------- -------- --------

A simple Java set of instructions (commands):

System.out.println("Java Sample Program"); System.out.println(); int x = 7; // declares a variable called x and then stores 7 in the box. int y = 5; // declares a variable called y and then stores 5 in the box. int answer = x + y; // This will print The answer is 12 System.out.println("The answer is " + answer);

Another simple Java set of instructions (commands):

NOTES: 1) The // tells the compiler (translator) to ignore the rest of the line 2) This is a complete program. import java.util.*; public class Main { public static void main(String [] args) { // The variable input will refer to a Scanner object. // A Scanner object knows how to stop and // wait for the user to enter something from // the keyboard. // A Scanner object has several different methods // that can read the data entered by the user. // input.nextLine(); Reads the data typed in and returns a String. // input.next(); Reads the data typed in and returns the next element as a String. // input.nextInt(); Reads the data typed in and returns it as an Int // input.nextDouble(); Reads the data typed in and returns it as a Double Scanner input = new Scanner(System.in); System.out.println("Java Sample Program 2"); System.out.println(); System.out.print("Enter your first name: "); // ask the user to enter some data String firstName = input.nextLine(); // waits for the user to enter data and then returns it as String System.out.println(); System.out.println("Your first name is " + firstName); } // end of method main } // end of class Main

Some examples of illegal variable names:

Variable names must start with a letter of the alphabet, and preferably a lower case letter (by agreement). After the first letter, you can use more letters or digits or the underscore (_). Some invalid names. total Sum num@ sum!
Back to the Top
=================================
=================================

Programming Assignments

=================================
=================================



Back to the Top

Unit0a Labs


Unit0a Lab01 ASCII Box 1



// YOUR NAME: FIRST LAST
// CLASS PERIOD: ??
// Unit0a - Lab01 - ASCII Box
// 2021

class Main 
{
	public static void main(String[] args)
	{
		System.out.println("name \t  date \n\n" );//replace name and date
		System.out.println("\n\nAsciiBox 2021 \n\n" ); //leave as is. 
		System.out.println("+++++++++++++++++++++++++" );
		System.out.println("+++++++++++++++++++++++++" );
		
		// add more println statements to finish the design






		System.out.println("\n\nAsciiBox  2021"); //leave as is.
	}
}

Unit0a Lab02 ASCII Box 2



// YOUR NAME: FIRST LAST
// CLASS PERIOD: ??
// Unit0a - Lab02 - ASCII Box 2
// 2020

public class Main
{
	public static void main(String[] args)
	{
		System.out.println("name \t  date \n\n" );
		System.out.println("\n\nAsciiBox2 2021 \n\n" );
		System.out.println("+++++++++++++++++++++++++ " );
		System.out.println("+++++++++++++++++++++++++ ");
		
		// add more lines of code to println your Ascii Box 2








		System.out.println("\n\nAsciiBox2  2021"); // leave as is
	} // end of method
    
} // end of class

Unit0a Lab03 ASCII Art



// YOUR NAME: FIRST LAST
// CLASS PERIOD: ??
// Unit0a - Lab03 - ASCII Art
// 2021

public class Main
{
	public static void main ( String[] args )
	{
		System.out.println("Your Name \t  Date \t Period\n\n" );
		System.out.println("\n\nReplace This with the Title of your Art" );
		System.out.println("\n\nAsciiArt 2021 \n\n" );


		// write your instructions (statements, commands) below
		
		// you can replace this triangle shape with your own characters
		// to create your own design
		System.out.println("                /\\                " );
		System.out.println("               /  \\               " );
		System.out.println("              /    \\              " );
		System.out.println("             [------]             " );
		//add other output


		// the lines below are just reminders - do not delete them
		System.out.println(" \n\n\n\nHelpFul Hints" ); // leave as is
		System.out.println("\\\\ draws one backslash on the screen!\n" ); //leave as is
		System.out.println("\\\" draws one double quote on the screen!\n" ); //leave as is
		System.out.println("\\\' draws one single quote on the screen!\n\n\n" ); // leave as is
		System.out.println("\nAscii Art 2021" ); // leave as is
	} // end of method
    
} // end of class


Unit0b Labs


Unit0b Lab01 Variables



// YOUR NAME: FIRST LAST
// CLASS PERIOD: ??
// Unit0b - Lab01 - Variables
// 2021

public class Main
{

    // define 1 variable of each of the
    // following data types and then give each
    // variable a value.  The first couple are 
    // done for you.
    // byte short       int         long
    // float    double
    // char      boolean    String

 public static void main ( String[] args )
 {

  System.out.println("Your Name \t  Date \t Period\n\n" );
  System.out.println("\n\nReplace This with the Title of Variables" );
  System.out.println("\n\nVariables 2020 \n\n" );

  // define 1 variable as a byte and assign it 127 (this is done for you)
  byte byteOne = 127;  

  // define 1 variable as a short and assign it -32123 (this is done for you)
  short shortOne = -32123; 
   
  char charOne = 65;
  
  String firstName = "James";

  // define all other variables


  //output your information here
  System.out.println("/////////////////////////////////");
  System.out.println("*Your Name              ??/??/19*");
  System.out.println("*                               *");
  System.out.println("*        Integer Types          *");
  System.out.println("*                               *");
  System.out.println("*8 bit - byteOne = " + byteOne);
  System.out.println("*16 bit - shortOne = " + shortOne);
  
  // add more println statements to print out all other info




 } // end of method main
 
} // end of class

/*
Sample Output : 

/////////////////////////////////
*Some Person            05/15/19*
*                               *
*        INTEGER TYPES          *
*                               *
*8 bit - byteOne = 127          *
*16 bit - shortOne = -32123     *
*32 bit - intOne = 90877        *
*64 bit - longOne = 999999999   *
*                               *
*         REAL TYPES            *
*                               *
*32 bit - floatOne = 38.5678    *
*64 bit - doubleOne = 923.234   *
*                               *
*      OTHER INTEGER TYPES      *
*                               *
*16 bit - charOne = A           *
*                               *
*         OTHER TYPES           *
*                               *
*booleanOne = true              *
*stringOne = hello world        *
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


*/

Unit0b Lab02 All About Me



// YOUR NAME: FIRST LAST
// CLASS PERIOD: ??
// Lab02 - All About Me
// 2021
//
// This program practices declaring, assigning and ouputing variables
// of different data types.
//

class Main
{
    public static void main (String args[])
    {
        System.out.println("APCS 2021  name                 date ");
        
        /* Declare variables with the following data types. A description
         * of the variable's purpose should help you choose a meaningful 
         * identifier.  These are declarations only!
         *
         * byte - your age
         * int - # of text messages you sent in August
         * float - your shoe size
         * double - I couldn't think of anything! Make something up! (Must have decimal!)
         *
         * char - your gender
         * boolean - you love mexican food
         * String - favorite color
         * String - favorite song   */
    

        // DO IT BELOW THE 3 ROWS OF ******
        // *******************************************************
        // *******************************************************
        // *******************************************************
        // I've done the first two for you. You do the rest(see comments above)
    
        // First declare the variables, but DO NOT ASSIGN A VALUE
        byte myAge;
        int  numTextMessages;       
        // DO THE REST of the declarations  
        
        
        
        
        
        
        // DO IT BELOW THE 3 ROWS OF ******
        // Now assign your variables some value.
        // See my example. Feel free to change the values.
        // The first two are done for you.
        // *******************************************************
        // *******************************************************
        // *******************************************************
        
        myAge = 29;
        numTextMessages = 1867; 
        // now do the rest of the assignments
        
        
        
        
        
        // At this point in the program, using println statements,
        // output your mailing label. It should look something like this...
        // 
        //      Ms. Minnie Mouse
        //      1234 Walt Disney Way
        //      Hollywood, CA  90210
        //      
        // DO IT BELOW THE 3 ROWS OF ******
        // print out your mailing label here
        // I have done the first two lines for you        
        // *******************************************************
        // *******************************************************
        // *******************************************************
        System.out.println();
        System.out.println("      Ms. Minnie Mouse");
        // Finish the label here





        // DO IT BELOW THE 3 ROWS OF ******
        // Now, print out the values of all of your variables
        // See how I included a meaningful message concatenated with your variable
        // The first two are done for you.
        // *******************************************************
        // *******************************************************
        // *******************************************************      
        System.out.println(" My age is -----> " + myAge);
        System.out.println();
        System.out.println(" Text messages sent -----> " + numTextMessages);
        System.out.println();
        // ADD MORE println statements here to finish printing out 
        // the values of all of your variables and a meaningful message
            
            
            
            
            
        System.out.println(" \nTHE END !!!  ");
        System.out.println("APCS 2021");
        System.out.println();
        System.out.println();   
        
        
    } // end of method main
    
} // end of class


Unit0c Labs - User Input


Unit0c Lab01 Keyboard Input



// YOUR NAME: FIRST LAST
// CLASS PERIOD: ??
// Unit 0c Lab01 - Input 
// 2021

import static java.lang.System.*;
import java.util.Scanner;

public class Main
{

    // The code in method main below will be run
    // or executed when you hit the Run Button.
    // This method must be called main since it
    // is the main starting point.
    public static void main (String[] args)
    {
        // The command new Scanner(System.in)
        // creates a Scanner object that can read from
        // the keyboard.  
        
        // Objects can have variables which contain 
        // data or memory addresses, and they also contain 
        // methods which contain computer code, and other stuff.
        
        // The variable keyboard receives the memory location of
        // where the Scanner object is stored in RAM memory.
        
        // There are quite a few methods that you can
        // call or invoke, which means that it will run
        // or execute the code that is in the method.
        // Sometimes we call a method a function.
        
        // keyboard.nextLine() reads in the user data 
        //     as a String
        // keyboard.nextInt() reads in the user data 
        //     and converts it to an int
        // keyboard.nextDouble() reads in the user data 
        //     and converts it to a double
        // keyboard.nextFloat() reads in the user data 
        //     and converts it to a float
        // keyboard.nextShort() reads in the user data 
        //     and converts it to a short
        
        Scanner keyboard = new Scanner(System.in);

        // This define's variables of different types
        int intOne, intTwo;
        double doubleOne, doubleTwo;
        float floatOne, floatTwo;
        short shortOne, shortTwo;

        System.out.println();
        // PUT YOUR NAME ON THE OUTPUT
        System.out.println("First Name   Last Name");
        System.out.println();
        
        // Here we prompt the user to enter an integer.
        // keyboard.nextInt() waits for the user to enter an integer,
        // and then reads in the number that the user enters,
        // and it better be an integer number or we crash
        // Notice that the number is stored in the variable intOne
        System.out.print("Enter an integer :: ");
        intOne = keyboard.nextInt();


        // Here we prompt the user to enter another integer
        // and then read it in.
        // Notice that the number is stored in the variable intTwo
        System.out.print("Enter an integer :: ");
        intTwo = keyboard.nextInt();

        // ****************************************
        // Add in input for all the other variables
        // Follow the pattern used above.
        // ****************************************






        // Now we print out a message and the value of each variable.
        // You will need to do the same thing for all the other variables.
        System.out.println();
        System.out.println("integer one = " + intOne );
        System.out.println("integer two = " + intTwo );
        System.out.println();

        // Add in output for all the other variables
        // Follow the pattern above with the two ints
        
        
        
        


    } // end of method main
    
} // end of class Main

Unit0c Lab02 Slope of a Line



// YOUR NAME: FIRST LAST
// CLASS PERIOD: ??
// Unit 0c Lab02 - Slope of a Line
// 2021


import java.util.Scanner;

public class Main // Slope.java
{        
    
    public static void main(String[] args) 
    {
        System.out.println();
        System.out.println("First Name   Last Name");
        System.out.println();
        System.out.println("Slope of a Line");
        System.out.println("APCS 20-21");
        System.out.println();
        System.out.println();
        
        
        // create a Scanner object so that
        // we can read in data from the keyboard
        Scanner scan = new ??????? (??????.??);
        
        double x1;  // the x value of the first point
        double y1;  // the y value of the first point
        
        double x2;  // the x value of the second point
        double y2;  // the y value of the second point
        
        double slope;  // holds the slope of the line
        
        
        System.out.println("Slope of a Line");
        System.out.println();
        System.out.println();
        
        // here we prompt the user to enter the x value for the first point 
        // and then we read it in.
        // NOTE: Notice that we use print and NOT println!
        System.out.print("Enter x1 ");
        x1 = scan.nextDouble();
        
        // prompt the user to enter y1 
        // and then read it in


      
        System.out.println();
        

        // prompt the user to enter x2 
        // and then read it in


        // prompt the user to enter y2 
        // and then read it in
        
        
        System.out.println();
        
        
        // calculate the slope using the correct formula
        // change of y values divided by the change in x values
        // (?????) / (??????)
        
        slope = ?????;
        
        // now print out "The slope of the line is" concatenated with the slope


        System.out.println();
        System.out.println();
                
    } // end of method main
  
}  // end of class Slope

/*
Sample Run:

John Doe

Slope of a Line
APCS 2021


Slope of a Line


Enter x1 1
Enter y1 2

Enter x2 4
Enter y2 8

The slope of the line is 2.0

*/

END OF ASSIGNMENTS (MORE COMING!)


Unit14 - Sample Program Arrays




import java.util.*;
import java.io.*;

public class HelpArrays
{
  public static void main(String [] args)
  {
    System.out.println("Java Arrays");
    System.out.println();
    System.out.println();

/*
An Array is a class!
Remember that a class is a container.
It contains mainly variables and methods.
(and constants and constructors)

The Array class
===============

A class is a container.  
It contains ????


Variables
---------
A list of elements or items that we define.
They must be all of the same data type.
You can not change the length of an array!
Once created, that is it.

Example 1: int [ ] list = new int[5];
           
           Creates 5 int variables (boxes).
           The variables are all set to 0.

Think of a series of boxes (int variables)
indexes       0      1       2      3      4
          -------------------------------------
 list --- |   0  |   0   |   0  |   0  |   0  |
          -------------------------------------
 
Example 2: int [ ] list = { 98, 100, 76, 85, 99 };
           Creates 5 int variables (boxes).

 Think of a series of boxes (int variables)
 indexes      0      1       2      3      4
          -------------------------------------
 list --- |  98  |  100  |  76  |  85  |  99  |
          -------------------------------------
  
  
Constants (Variables marked as final)
-------------------------------------
length   (public final int length = ?;)
This final int variable holds the number of
items or elements.  
NOTE: IT IS NOT A METHOD, so no ( )

Methods in an Array Object:
---------------------------
None (of it's own, however it does inherit some methods)
(More about inheritance later)
*/

    
    // *********************************************
    // Example 3:
    // *********************************************
    //   Strings actually store the chars in an array.
    //   Think of a series of boxes (char variables).
    //   indexes       0       1       2
    //             ------------------------
    // letters --- |   B   |   o   |   b  |
    //             ------------------------
    
    char [ ] letters = {'B', 'o', 'b'};
    
    letters[0] = 'R'; // changes 'B' to 'R' in position 0
    
    // prints out:
    // R
    // o
    // b 
    System.out.println();
    System.out.println("Example 3: letters");
    for (int i=0; i ? letters.length; i++)
    {
      System.out.println(letters[i]);
    }
    


    // *********************************************
    // Example 4:
    // *********************************************
    //
    //   Think of a series of boxes (String variables)
    //   indexes      0       1     2
    //             ----------------------
    // players --- | Bill  | Sue | Jill |
    //             ----------------------

/*
    String [ ] players = {"Bill", "Sue", "Jill"};
    
    players[0] = "Tim"; // changes "Bill" to "Tim" in position 0
    
    // prints out:
    // Tim
    // Sue
    // Jill 
    System.out.println();
    System.out.println("Example 4: players");
    for (int i=0; i ? players.length; i++)
    {
      System.out.println(players[i]);
    }
    
*/
    

/*
    // *********************************************
    // Example 5:
    // *********************************************
    //
    //   Think of a series of boxes (String variables)
    //   indexes      0       1     2
    //             ----------------------
    // players --> | Bill  | Sue | Jill |
    //             ----------------------
    
    String  [ ]  players = new String[3]; 
    players[0] = "Bill";
    players[1] = "Sue";
    players[2] = "Jill";    
    players[0] = "Tim"; // changes "Bill" to "Tim" in position 0
    
    // prints out:
    // Tim
    // Sue
    // Jill 
    System.out.println();
    System.out.println("Example 5: players");
    
    // A for each loop!
    // Variable player will receive 1 item from players
    // each time through the loop.
    
    // General Structure of a for each loop.
    // for ( variable to hold 1 item : the list)
    
    for (String player : players)
    {
      System.out.println(player);
    }
*/
    
    

    // *********************************************
    // Example 6:
    // *********************************************
    //
    //   Think of a series of boxes (int variables)
    //   indexes       0      1       2
    //             -----------------------
    //  grades --- |  98  |  100  |  95  |
    //             -----------------------
    
    int [ ] grades = new int[3]; 
    grades[0] = 98;
    grades[1] = 100;
    grades[2] = 95;    
    grades[0] = 99; // changes 98 to 99 in position 0
    
    // prints out:
    // 99 100 95
    System.out.println();
    System.out.println("Example 6: grades");
    for (int i=0; i ? grades.length; i++)
    {
      System.out.print(grades[i] + " ");
    }
    System.out.println();

    System.out.println();
    double sum = 0;
    for (int i=0; i ? grades.length; i++)
    {
        sum = sum + grades[i];
    }
    System.out.println("Your grade is: " + sum/grades.length);
    System.out.println();
 
    
    
    
    // Let's count the number of even numbers
    // *********************************************
    // Example 7:
    // *********************************************
    //
    //   Think of a series of boxes (int variables)
    //   indexes         0      1       2      3      4
    //               -------------------------------------
    //   numbers --- |  98  |  100  |  95  |  72  |  99  |
    //               -------------------------------------
    
    int [ ] numbers = new int[5]; 
    numbers[0] = 98;
    numbers[1] = 100;
    numbers[2] = 95;    
    numbers[3] = 72; 
    numbers[4] = 99; 
    
    
    // prints out:
    // 98 100 95 72 99
    System.out.println();
    System.out.println("Example 7: Even numbers");
    for (int i=0; i ? numbers.length; i++)
    {
      // print out 1 number from the list numbers
      System.out.print(numbers[i] + " ");
    }
    System.out.println();

    int numEvens = 0;
    for (int i=0; i ? numbers.length; i++)
    {
        // Check to see if the ith number in the numbers 
        // list is an even number.  If so, add 1 to the 
        // variable numEvens.
        if (numbers[i] % 2 == 0)
            numEvens++;
              
    }
    System.out.println("Number of Evens: " + numEvens);
    System.out.println();
       

    
    
    
    // Let's find our shopping list bill.
    // *********************************************
    // Example 8:
    // *********************************************
    //
    //   Think of a series of boxes (double variables)
    //   indexes         0      1      2      3      4
    //               ------------------------------------
    //     items --> | 9.40 | 1.29 | 0.50 | 4.99 | 2.79 |
    //               ------------------------------------


    double  [ ]  items =  new double[5]; 
    items[0] = 9.40;
    items[1] = 1.29;
    items[2] = .50;    
    items[3] = 4.99; 
    items[4] = 2.79; 
    
    
    // prints out:
    // 9.4 1.29 0.5 4.99 2.79
    System.out.println();
    System.out.println("Example 7: Prices");
    for (int i=0; i ? items.length; i++)
    {
      // print out 1 item
      System.out.print(items[i] + " ");
    }
    System.out.println();

    double totalBill = 0;
    for (int i=0; i ? items.length; i++)
    {
       totalBill += items[i]; 
    }
    System.out.println("Total Bill: " + totalBill);
    System.out.println();
       
    
  } // end of method main
  
} // end of public class HelpArrays






=================================
=================================

End of Programming Assignments

=================================
=================================

Back to the Top

Extra Credit Labs


Extra Credit 1 - Reading from a file student information

import java.util.*; // for Scanner from Java 1.5, 1.6, etc., and ArrayList import java.io.*; // for file input import static java.lang.System.*; // so that you don't have to do System. public class Main { // no instance variables are needed public static void main(String[] args) throws IOException { // print out your name // create a new Scanner object Scanner input = ??? ???????(new File("student.dat")); // allows you to read in the data from a file called student.dat // USE: // input.nextLine() to read in an entire line // from the file as a String // input.nextInt() to read in the next element // and convert it to an int // input.nextDouble() to read in the next element // and convert it to an double // READ IN THE DATA FROM THE FILE // The contents of the file // Line 1: First name of the student // Line 2: Last name of the student // Line 3: School ID // Line 4: 3 Test Grades (each element separated by a space) // Line 5: 5 Homework Grades (each element separated by a space) // Sample File: You will need to create the file and copy this info. // Then delete the info in this file. /* John Smith JS78754 85 82 65 75 82 65 67 88 */ // Read in the first name (this has been done for you) String firstName = input.nextLine(); // Read in the last name String lastName = input.???????; // Read in the school ID String schoolID = ??????; // Read in the 3 Test Grades one by one int test1 = input.nextInt(); int test2 = input.???????; int test3 = ?????.???????; // Now we will move the file cursor to the next line input.nextLine(); // Read in the 5 Homework Grades one by one - use input.nextInt() int hw1 = ?????; int hw2 = ?????; int hw3 = ?????; int hw4 = ?????; int hw5 = ?????; // Now we will move the file cursor to the next line input.?????; // find the test average // Make sure that your calculation does not chop off the // the decimal part double testAverage = ??????; // find the home work average // Make sure that you do double arithmetic double homeworkAverage = ?????????; // print out the output // print the first name and last name separated by a space System.out.println("Name: " + ????? + ????? + ?????); // print out the ID number System.out.println("ID: " + ????????); // Skip a line (blank) System.out.???????; // print the 3 test grades all on the same line separated by a space // Use printf and print each grade with the format code %4d // test1 should fill the first %4d // test2 should fill the second %4d // test3 should fill the third %4d // The arguments fill the %4d from left to right // An example is shown at the bottom System.out.printf("Tests: %4d %4d %4d\n", ?????, ?????, ?????); // Skip a line (blank) System.out.??????; // print the 5 homework grades all on the same line // separated by a space // Use printf and print each grade with the format code %4d // Remember the arguments fill from left to right System.out.printf("Homework: %4d %4d %4d %4d %4d\n", ?????); // Skip a line (blank) System.???.????; // print the test average rounded to 2 decimal places - Use printf %.2f System.out.printf("Test Average: ????\n", ?????); // print the homework average rounded to 2 decimal places - Use printf %.2f System.out.printf("Homework Average: ????\n", ???????); // Skip a line (blank) ????????????? // Calculate the average // 70% of the testAverage plus 30% of the homeworkAverage. // Remember of means multiply (*) // Use .7 not 70% in your code // Use .3 not 30% in your code double average = ?????????????; // print out the overall grade (average) // USE printf and %.6f (round to 6 decimal positions) System.out.printf("Average: ????\n", ?????); // Skip a line (blank) ????????? // NOTE: to print using a certain number of print positions // use System.out.printf (See example below) // System.out.printf("some string with replacement codes", // list of arguments for the replacement codes); // The %-20s means left justify the String "Homework Average : " // using 20 print positions. The s means the argument must // be a String. The minus means left justify. // The %6.2f means take up at least 6 print positions and round // the result to 2 decimal places. // The f means the argument must be a double or a float // A d means the argument must be an integer (int) // Example: // System.out.printf("%-20s %6.2f \n","Homework Average :",homeworkAverage); input.close(); } // end of main method } // end of class /* Sample Output: Name: John Smith ID: 78754 Tests: 85 82 65 Homework: 75 82 65 67 88 Test Average: 77.33 Homework Average: 75.40 Average: 76.753333 */

Extra Credit 2 - Reading from a file army time



/*
EXTRA CREDIT
EXPLANATION (Sample Skeleton code is below)
Program Name: ArmyTime.java (Main.java for repl.it)

Data File:    armytime.dat


You have been given the task of converting army time
into our time.

For example:  

0900 hours is  9:00 o'clock.
0930 hours is  9:30 o'clock. 
1100 hours is 11:00 o'clock.
1100 hours is 11:00 o'clock.
1145 hours is 11:45 o'clock.
1600 hours is  4:00 o'clock.  (1600 - 1200 or 1600 % 1200)
1615 hours is  4:15 o'clock.  (1615 - 1200 or 1615 % 1200)



Input:
======   
The first line of the input contains an integer n that represents the number 
of data sets that follow where each data set is on a single line.  Each data 
set contains 1 line which contains the army time.

  
Output:
=======   
Your program should produce n lines of output.  1 line for each data item.
 
The output is to be formatted exactly as shown.

You will need to create a file called armytime.dat
and copy this data into it starting with the 6.
Input:
======
6
9 0
9 30 
11 0
11 45
16 0
16 15



Output: (must be exact)
=======================  

 9  0 hours is  9:00 o'clock.
 9 30 hours is  9:30 o'clock. 
11  0 hours is 11:00 o'clock.
11 45 hours is 11:45 o'clock.
16  0 hours is  4:00 o'clock. 
16 15 hours is  4:15 o'clock. 

You will need to use System.out.printf() to format
this properly.

Example:
System.out.printf("%2d %2d hours is %2d:%2s o'clock.", 
                   armyHour, armyMinutes, ourHour, ourMinutesAsString);

In order to get the ourMinutesAsString:

if (ourMinutes < 10)
{
    ourMinutesAsString = "0" + ourMinutes;
}
else
{
    ourMinutesAsString = "" + ourMinutes;
}
*/

// HERE IS THE Skeleton CODE
import java.util.*; // for Scanner from Java 1.5, 1.6, etc., and ArrayList
import java.io.*;   // for file input
import static java.lang.System.*; // so that you don't have to do System.

public class Main
{
 // no instance variables are needed
 
 
 public static void main(String[] args) throws IOException
 {

  // print out your name


  // create a new Scanner object   
  Scanner input = new Scanner(new File("armytime.dat")); // reads in the data file  
   

  
  // read in the first line from the file and convert it to an int
  // this number is the number of data sets in the file
  int lines = input.nextInt();
  
  input.nextLine(); // this moves the cursor to the next line in the file
    
  
  // you will now need a loop to loop through all the data sets 
  
  for (int k=0; k < lines; k++)
  {      
       // solve the problem
       // read in the army time         
       
       int armyHour = input.nextInt();
       int armyMinutes = input.nextInt();       

       // You will need to define the following variables
       // and assign the proper values.
        
       // find ourHour
       // find ourMinutes
       // find ourMinutesAsString


       // Now print the results.
      
  }
  
  
  
   
  input.close();

 } // end of main method

 
} // end of class


Extra Credit 3 - Reading from a file

Vowels and Digits Program Name: VowelsAndDigits.java Input File: sentences.dat This program will read in a several sentences one at a time from the file sentences.dat Your program will modify each sentence by doing the following: 1) It will change all characters to lower case. 2) It will swap vowels with another vowel. a will become u. u will become a. e will become o. o will become e. i will stay the same. 3) It will swap any digits with other digits. 0 will become 9. 1 will become 8. 2 will become 7. 3 will become 6. 4 will become 5. 5 will become 4. 6 will become 3. 7 will become 2. 8 will become 1. 9 will become 0. You will need to make your own data file and name it sentences.dat Example input: ============== He made $65,439.01 dollars last year. I made a 100 on my test! Example output: =============== He made $65,439.01 dollars last year. Ho mudo $34,560.98 dellurs lust your. I made a 100 on my test! I mudo u 899 en my tost! import java.util.*; // for Scanner from Java 1.5, 1.6, etc., and ArrayList import java.io.*; // for file input import static java.lang.System.*; // so that you don't have to do System. public class Main { // no instance variables are needed public static void main(String[] args) throws Exception { // print out your name // create a new Scanner object Scanner input = ??? ??????(new File("sentences.dat")); // reads in the data file // You will now need to read in the number of data sets (sentences) int lines = input.????; // you will now need a loop to loop through all the data sets for ( ????? ) { // solve the problem // NOTE: The scanner class has methods nextInt(), nextDouble(), // next() (for 1 word), and nextLine() (the entire line) // Read in the next sentence from the file String sentence = input.?????? // loop through all the characters 1 by 1 // A String has a length() method that returns the number // of characters (including spaces, etc.) // Suppose your String variable is called s. // Suppose that i is an int variable that holds some valid index. // Characters are indexed by positions from 0 to s.length()-1 // The String "cat" has indexes from 0 to 2. // The c is in position 0 or has an index of 0. // The a is in position 1 or has an index of 1. // The t is in position 2 or has an index of 2. // A String has lots of methods, so here are some of them. // s.length() returns the number of characters in the String // s.substring(i,i+1) returns the ith character as a String // s.charAt(i) returns the ith character as a char // s.toLowerCase() returns a new String with all letters being // in lower case, and all other characters left the same. // // Suppose s is referring to String "cat" and i is 0. // s.length() returns 3 // s.substring(i,i+1) returns "c" // s.charAt(i) returns 'c' (character c) // // A String is immutable, meaning you can't change it. // However, you can build a new String from it. // ns = ns + s.charAt(i); // or ns = ns + s.substring(i,i+1); s = s.toLowerCase(); // s will now refer to different String for (??? i=0; i ? ???; i++) { // get the character at the i position (at index position i) char ch = s.????(i); // next, change the value of ch according to the rules above // finally update the String reference variable ns // by adding the character to the end of ns. ns = ?? + ??; } // end of inner for loop // print out the original String s // print out the new String (ns) // print a blank line } // end of for loop input.close(); } // end of main method } // end of class

Extra Credit 4 - Graphics Big House

// Labs Chapter 3 Set 2 // Main.java and BigHouse.java // Draw a house with a roof, a door, // 2 windows, and a sun in the sky. // Use different colors. // FINISH ME // Name: Your full name goes here NOTE: YOU MUST USE the JavaSwing class type compiler, NOT the Java language compiler. import javax.swing.JFrame; public class Main extends JFrame { // The keyword static means that there will be only 1 variable called WIDTH // and it will be loaded into memory at the start of the run. // The keyword final means that you cannot change the value of the variable. // (thus it is a constant) private static final int WIDTH = 800; private static final int HEIGHT = 600; public Main() { // FINISH ME super("Graphics Runner written by YOUR NAME"); setSize(WIDTH,HEIGHT); // FINISH ME // create a different class to run // another graphic lab // BigHouse, Robot, or ShapePanel getContentPane().add(new SmileyFace()); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // This is where your program gets started public static void main( String args[] ) { Main run = new Main(); } } // end of class Main // Lab Chapter 3 Set 2, Lab 2 // BigHouse.java // FINISH ME // Name: Your full name goes here import java.awt.Graphics; import java.awt.Color; import java.awt.Canvas; public class BigHouse extends Canvas { public BigHouse() //constructor - sets up the class { setSize(800,600); setBackground(Color.WHITE); setVisible(true); System.out.println("Running BigHouse - Lab Chap. 3 Set 2 Lab 2"); // FINISH ME System.out.println("Written by Your Name"); } public void paint( Graphics window ) { // FINISH ME // call bigHouse and send it the value of variable window (memory address) } public void bigHouse( Graphics window ) { window.setColor(Color.BLUE); // (0,0) is the upper left point of the window. // move over 35 pixels and then down 40 pixels (x,y) // and start drawing the text window.drawString( "BIG HOUSE ", 35, 40 ); // FINISH ME window.drawString("YOUR NAME ", 35, 60); window.setColor(Color.BLUE); window.fillRect( 200, 200, 400, 400 ); // FINISH ME } // end of method bigHouse } // end of class BigHouse /* (0,0) is the upper left point of the window. Built in methods: Call with the graphics reference variable which we called window. Example: window.drawLine(100, 50, 200, 50); void drawLine(int x1, int y1, int x2, int y2) void fillRect(int x, int y, int width, int height) void drawRect(int x, int y, int width, int height) void clearRect(int x, int y, int width, int height) void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) void draw3DRect(int x, int y, int width, int height, boolean raised) void fill3DRect(int x, int y, int width, int height, boolean raised) void drawOval(int x, int y, int width, int height) void fillOval(int x, int y, int width, int height) void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) void drawPolygon(Polygon p) void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) void fillPolygon(Polygon p) void drawString(String str, int x, int y) Color myColor = new Color(255,0,0); // red, white, blue in the range of 0..255 Color currentColor = window.getColor(); window.setColor(Color.red); Font myFont = new Font("Serif", Font.ITALIC, 24); window.setFont(myFont); window.setColor(Color.blue); window.drawString("Here is a message", 15, 25); */

Extra Credit 5 - Graphics Robot

// Labs Chapter 3 Set 2 // Main.java and Robot.java // FINISH ME // Name: Your full name goes here // NOTE: YOU MUST USE the JavaSwing class type, // NOT the Java language compiler. import javax.swing.JFrame; public class Main extends JFrame { // The keyword static means that there will be only 1 variable called WIDTH // and it will be loaded into memory at the start of the run. // The keyword final means that you cannot change the value of the variable. // (thus it is a constant) private static final int WIDTH = 800; private static final int HEIGHT = 600; Robot robot = null; public Main() { // FINISH ME super("Graphics Runner written by YOUR NAME"); setSize(WIDTH,HEIGHT); // FINISH ME // create a different class to run robot = new Robot(100,120,20,20); getContentPane().add(robot); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // This is where your program gets started public static void main( String args[] ) { Main run = new Main(); while (true) { try { Thread.sleep(30); run.robot.moveRight(); run.robot.repaint(); } catch (Exception e) { } } } } // end of class Main // Lab Chapter 3 Set 2, Lab 3 // Main.java and Robot.java // FINISH ME // Name: Your full name goes here import java.awt.Graphics; import java.awt.Color; import java.awt.Canvas; class Robot extends Canvas { private int x; private int y; private int width; private int height; public Robot(int x, int y, int width, int height) // constructor method - sets up the class { setSize(800,600); setBackground(Color.WHITE); setVisible(true); this.x = x; this.y = y; this.width = width; this.height = height; System.out.println("Running Robot - Lab Chap. 3 Set 2 Lab 3"); // FINISH ME System.out.println("Written by Your Name"); } public void moveRight() { x = x + 5; if (x > 800) { x = -width; } } public void paint( Graphics window ) { window.setColor(Color.BLUE); window.drawString("Robot LAB ", 35, 35 ); // FINISH ME window.drawString("YOUR NAME ", 35, 55); // ALL drawings must be releative to where // x and y are located. // call head method head(window); // call other methods (upperBody and lowerBody) } public void head( Graphics window ) { window.setColor(Color.YELLOW); window.fillOval(x, y, width, height); // FINISH ME // add more code here } public void upperBody( Graphics window ) { // FINISH ME // add more code here } public void lowerBody( Graphics window ) { // FINISH ME // add more code here } } // end of class Robot

Extra Credit 6 - Scramble

// Main.java and scramble.dat // FINISH ME // Name: Your full name goes here import java.util.*; // for Scanner from Java 1.5, 1.6, etc., and ArrayList import java.io.*; // for file input import static java.lang.System.*; // so that you don't have to do System. // You will be reading in a text file. // The text file (scramble.dat) contains: // (you will need to make your own file) // Remove the // in your data file. //4 //S I love computer science. //U I gjq` ^jhkpo`m n^d`i^`. //S I love programming, who doesn't? //U I gjq` kmjbm\hhdib, rcj _j`ni'o? // The 4 means that you have 4 data sets to read. // The S means to scramble the following sentence. // The U means to unscramble the following sentence. // The output should be: // I gjq` ^jhkpo`m n^d`i^`. // I love computer science. // I gjq` kmjbm\hhdib, rcj _j`ni'o? // I love programming, who doesn't? // If you have an S, then scramble // by adding 5 to each lower case letter, and // otherwise just add the character. // NOTE: The scanner class has methods nextInt(), nextDouble(), // next() (for 1 word), and nextLine() (the entire line) // nextLine() will also move the file cursor to the next line // NOTE: The String class has methods length(), charAt(position), // substring(position), substring(position, stop position), // and more! // NOTE: a char + an int is an int result (promotion) // Example: 'A' + 1 is integer 66 // ch = ch + 1; will give you an error // ch = (char) (ch + 1); will work public class Scramble { // no instance variables are needed public static void main(String[] args) throws Exception { // print out your name // create a new Scanner object // reads in the data file Scanner input = ??? ???????(new File("scramble.dat")); // You will now need to read in the number of data sets // call your input's nextInt() method. int lines = input.?????????; // Now flush the buffer // move the file cursor to the next line input.????????; // loop through each line of the data file for (int line=1; line <= ?????; ????++) { // solve the problem // Get the first character as a String // It should be an "S" or a "U" // (you want the character by calling next() String method = input.??????; // Get the sentence to convert // Read in the entire rest of the line String sentence = input.????????; // remove the beginning space character from the sentence. sentence = sentence.???????????; // this variable will hold the converted String String output = ""; if (method.equals("S")) { // we will loop through the sentence char by char // (we scramble) char by char and then add the // scrambled char to our output for (int i = ?; i < ???????; ???) { // get the next character from sentence char ch = sentence.????(i); // check and see if ch should be scrambled // the range to check for is 'a' through 'z' if (ch >= 'a' && ?????????) { // scramble it by subtracting 5 // however ch - 5 will result in an int // to store an int in a char you must use // a type cast ch = ???????? } // add ch to the end of your output output = ??????? } // end of for char by char // print out your output ????????????? } // end of if (method.equals("S")) else if (method.equals("U")) { // now unscramble char by char } // end of else if (method.equals("U")) } // end of for (int line=1; line<=n; line++) input.close(); } // end of main method } // end of class

Extra Credit 7 - PhoneNumber

import java.util.*; // for Scanner from Java 1.5, 1.6, etc., and ArrayList import java.io.*; // for file input import static java.lang.System.*; // so that you do not have to do System. public class PhoneNumbers { // no instance variables are needed // These static methods may help you. // Also, look at how these are written, and // finish them if they are not complete public static boolean isCharacter(char ch) { // this checks to see if ch is a capital letter // use single quotes for the char type if (ch ?= ??? && ch ?= ???) return true; // see if ch is a lowercase letter if (???????) return true; return false; } public static boolean isDigit(char ch) { // see if ch is greater than or equal to char 0 // and is less than or equal to char 9 if (?????????) return true; return false; } public static boolean isAllDigits(String s) { // loop through all the characters to see if // there is a non-digit character for (int i=0; i ? s.??????; i++) { // ask s to give you the character at position i char ch = s.?????(?); // if the character is less than '0' or // greater than '9' it is NOT a digit // so we are done if (????? || ch > ????? ) return false; } return true; } public static boolean isAlphaNumeric(String s) { // loop through all the characters // to see if there is a non-alphanumeric character for (int i=0; i ? s.??????; ???) { // get the character at the i position of s char ch = s.?????(?); // if the character is a letter or // it's a digit great // else we are done if ( isCharacter(ch) || isDigit(ch) ) ; else return false; } return true; } // does it have (999) at the beginning public static boolean hasLeadingParenthesis(String s) { // see if the length of s is less than 5 if (?????) return false; // check positions 0 and 4 // see if s has a "(" at pos 0 (use indexOf) // && see if s has ")" at pos 4 if ( (s.?????("(") == 0) && (s.?????(???) == 4) ) return true; return false; } // does it have (999) // 012345 public static boolean hasAreaCode(String s) { if (s.length() ? 6) return false; // see if s has a leading parenthesis and // ending parenthesis and then a space // in position 5 if (hasLeadingParenthesis(s) && s.?????? == ???) { return true; } return false; } public static void main(String[] args) throws Exception { // print out your name // create a new Scanner object Scanner input = ??? ???????(new File("phonenumbers.dat")); // reads in the data file // You will now need to read in the number of data sets (phone numbers) // use nextI??() int lines = input.????????; input.nextLine(); // this will move the file cursor down to the start of the next line // you will now need a loop to loop through all the data sets for ( int line=0; line ? lines; line++ ) { // solve the problem // NOTE: The scanner class has methods nextInt(), nextDouble(), // next() (for 1 word), and nextLine() (the entire line) // Read in the next phone number from the file (use nextLine()) // The phone numbers in the file will be in the form of // 999-AAA-AAAA OR (999) AAA-AAAA OR 999AAAAAAA // 999-AAA-AAAA OR (999) AAA-AAAA OR 999AAAAAAA // OR // None of these formats (which will be an error) // The 9 means there is a digit in that spot // The A means there is an alpha numeric character in that spot // or i.e. a digit or a letter // Note that 999AAAAAAA has 10 characters // Note that 999-AAA-AAAA has 12 characters // Note that (999) AAA-AAAA has 14 characters // YOU may assume that if the length is one of these // three lengths, it might be valid, but otherwise // would be considered invalid. // Your job is to get all phone numbers into the same format, // which is (999) AAA-AAAA // For example: // 512-720-9280 should become (512) 720-9280 for output // (512) 720-9280 should become (512) 720-9280 for output // 5127209280 should become (512) 720-9280 for output // 512729280 should become Invalid Input // Read in the next line in the file which may or may not // be a valid phone. String phoneNumber = input.nextLine(); // A String has a length() method that returns the number // of characters (including spaces, etc.) // A String has lots of methods, so here are some of them. // s.length() returns the number of characters in the String // s.substring(i,i+1) returns the ith character as a String // s.charAt(i) returns the ith character as a char // s.toLowerCase() returns a new String with all letters being // in lower case, and all other characters left the same. // s.indexOf("a string to search for") // // Suppose s is referring to String "cat" and i is 0. // s.length() returns 3 // s.substring(i,i+1) returns "c" // s.charAt(i) returns char c (character c is in the 0 position) // s.indexOf("t") returns 2 // // A String is immutable, meaning you can't change it. // However, you can build a new String from it. // ns = ns + s.charAt(i); // or ns = ns + s.substring(i,i+1); // We will change this if we find a valid input String newPhoneNumber = "Invalid Input"; // Decide what to do // Check for the lengths first to see if you can convert, and if // not, assign "Invalid Input" to newPhoneNumber // The length must be 10, 12, or 14 to have a chance of a // valid phone number that can be converted // Some if else if statements most likely will be your best shot // Let us handle this case first // 999AAAAAAA // 0123456789 if (phoneNumber.length() == 10) if (isAllDigits(phoneNumber.substring(0,3))) if ( isAlphaNumeric(phoneNumber.substring(3)) ) { newPhoneNumber = "(" + phoneNumber.substring(0,3) + ") " + phoneNumber.substring(3,6) + "-" + phoneNumber.substring(6); } // 999-AAA-AAAA // 012345678901 if (phoneNumber.length() == 12 && phoneNumber.charAt(3) == ??? && phoneNumber.charAt(7) == ??? ) if ( isAllDigits(phoneNumber.substring(0,3)) ) if ( isAlphaNumeric(phoneNumber.substring(4,7)) ) if ( isAlphaNumeric(phoneNumber.substring(8)) ) { // get the required pieces from phoneNumber // using substring (see first example) newPhoneNumber = "(" + phoneNumber.????? + ") " + ?????? + "-" + phoneNumber.substring(8); } // (999) AAA-AAAA has 14 characters // 01234567890123 if ( phoneNumber.length() == 14 && hasAreaCode(phoneNumber) ) if ( isAlphaNumeric(phoneNumber.substring(6,9)) ) if ( isAlphaNumeric(phoneNumber.substring(10,14)) ) { newPhoneNumber = ???? } // print out the original String s, then the new string // The format must be exactly like the output sample // Here is a statement to help you. // %-18s and %-14s are replacement codes. // %-18s means to print out phoneNumber left justified (-) // using 18 print positions. // %-14s means to print out newPhoneNumber left justified (-) // using 14 print positions. System.out.printf("%-18s%-14s\n", phoneNumber, newPhoneNumber); } // end of for loop input.close(); } // end of main method } // end of class /* Sample Input File: 7 512-7876-4456 512-7876-445 (512) 787-5000 (512)6787-5000 5127876445 800-GET-HELP 512-787-4456 Sample Output: 512-7876-4456 Invalid Input 512-7876-44 Invalid Input (512) 787-5000 (512) 787-5000 (512)6787-5000 Invalid Input 5127876445 (512) 787-6445 800-GET-HELP (800) GET-HELP 512-787-4456 (512) 787-4456 */

Extra Credit 8 - Postfix

import java.util.*; // for Scanner from Java 1.5, 1.6, etc., and ArrayList import java.io.*; // for file input import static java.lang.System.*; // so that you don't have to do System. public class Main // Postfix { // no instance variables are needed public static void main(String[] args) throws IOException { // print out your name // create a new Scanner object Scanner input = ??? ??????(new File("postfix.dat")); // reads in the data file // read in the first line from the file and convert it to an int // this number is the number of data sets in the file // int lines = ????.??????(); input.nextLine(); // this moves the cursor to the next line in the file // You will now need a loop to loop through all the data sets. // The variable lines tells you how many lines of data that you // need to process. for (int i=0; i ? ?????; i++) { // solve the problem // NOTE: The scanner class has methods nextInt(), nextDouble(), // next() (for 1 word), and nextLine() (the entire line) // NOTE: You will need to read in an int, another int, and a String // So, you will need a input.nextInt(), // input.nextInt(), and then an input.nextLine() // You will then need an if else if statement in order to // do the correct math operation and print the result. } input.close(); } // end of main method } // end of class // You will need to create your own data file. // Here is the data: /* The data file contains: 5 3 5 * 4 7 + 8 2 - 8 5 / 8 5 % Expected Output (Must be exact) 3 5 * = 3 * 5 = 15 4 7 + = 4 + 7 = 11 8 2 - = 8 - 2 = 6 8 5 / = 8 / 5 = 1 8 5 % = 8 % 5 = 3 */

Back to the Top

Sample Programs


Sample Program - Keyboard Input


  
// Sample Program to find the 
// Area of a Triangle

import java.util.*;


class Main {
  public static void main(String[] args) {

    // Creates a Scanner object.
    // You can get input from the user.
    // The variable kb will refer to the object.
    // The variable can be called kb,
    // or keyboard, or scan, or ?
    // Variables should always start with a
    // lower case letter, and then you can use
    // more letters or digits or an _

    Scanner kb = new Scanner(System.in);
    
    System.out.println("Area of a Triangle");
    System.out.println();
    System.out.println();

    // We prompt the user to enter the width
    // NOTE: we use print, NOT println()
    System.out.print("Enter the width: ");
    
    // The user should enter the width
    // We will convert the input to an int
    int width = kb.nextInt();
    kb.nextLine(); // flush the buffer

    // We prompt the user to enter the height.
    // NOTE: we use print, NOT println()
    System.out.print("Enter the height: ");

    // The user should enter the height.
    // We will convert the input to an int
    int height = kb.nextInt();
    kb.nextLine(); // flush the buffer

    // Here we calculate the area and store
    // the answer in the variable area.
    int area = width * height;

    // Skip a line before printing output
    System.out.println(); 

    // Finally, we print out the result.
    System.out.println("The area is " + area + " Square Units.");

  }
}



Back to the Top

Sample Program - Mod and div



import static java.lang.System.*;
import java.util.*;

class Main 
{
  public static void main(String[] args) 
  {
    out.println("Hello Math!");
    out.println();

/*
    // divide envenly 23 gold bricks
    int b = 23;
    b = b / 5;
    out.println("23 / 5 = " + b);
    out.println();
    
    // How many gold bricks are left over?
    b = 23;
    b = b % 5;
    out.println("23 % 5 = " + b);
    out.println();

    out.println("2 / 5 = " + (2/5));
    out.println("2.0 / 5 = " + (2.0/5));
    out.println("2 / 5.0 = " + (2/5.0));
    out.println("2 % 5 = " + (2%5));
    out.println("8 % 5 = " + (8%5));
    out.println("10 % 5 = " + (10%5));
    out.println();

    
    double x = (double)(3 / 2);
    out.println("3 / 2 = " + (3/2));
    out.println("(double) 3 / 2 = " + ((double)3/2));
    out.println("(double) (3 / 2) = " + ((double)(3/2)));
    out.println();
    out.println("5.0 + .5 = " + (5.0 + .5));
    out.println(".1 + .1 = " + (.1 + .1));
    


    double z = 7 + .2;
    out.println("z = " + z);
 */


/*   
    int a = 23;
    a /= 3 + 2;
    // same as a = a / (3 + 2);

    out.println("a = " + 23);
    out.println("a /= 3 + 2 is " + a);
    out.println();


    a = 5;
    a += 1 + 3 * 2;
    // same as a = a + (1 + 3 * 2);
    out.println("a = " + 5);
    out.println("a += 1 + 3 * 2 is " + a);
    out.println();

*/
    
    int a = 23;
    out.println("a = " + 23);
    a %= (3 + 2);
    out.println("a %= 3 + 2 is " + a);
    out.println();    
  

  
    a = 7;
    out.println("a = " + a);
    a++; // same as a = a + 1;  a += 1;
    a++;
    out.println("a++; a++; a is now " + a);
    out.println();    
  

    /*
    a = 7;
    out.println("a = " + a);
    a--;  // same as a = a - 7;  a -= 7;
    a--;
    out.println("a--; a--; a is now " + a);
    out.println();    
    */



    Scanner kb = new Scanner(System.in);
    
    out.println("Area of a Triangle");
    System.out.println();
    System.out.println();

    // We prompt the user to enter the width
    // NOTE: we use print, NOT println()
    out.print("Enter the width: ");
    
    // The user should enter the width
    // We will convert the input to an int
    width = kb.nextDouble();
    kb.nextLine(); // flush the buffer

    // We prompt the user to enter the height.
    // NOTE: we use print, NOT println()
    out.print("Enter the height: ");

    // The user should enter the height.
    // We will convert the input to an int
    double height = kb.nextDouble();
    kb.nextLine(); // flush the buffer

    // Here we calculate the area and store
    // the answer in the variable area.
    double area = width * height;

    // Skip a line before printing output
    out.println(); 

    // Finally, we print out the result.
    out.println("The area is " + area + " Square Units.");
*/


  } // end of main method

} // end of class Main (the container)



Back to the Top

Sample Program - Methods



import java.util.*;

// This is a class.

// I am a container.

// Classes contain instance variables which
//    always stick around
//    and keep my data for me.

// Classes contain methods which contain
//    computer code and do things.

public class Main
{
   
   // This is a method
   // A method (sometimes called a function) contains a block of code.

   // Methods must always have ().

   // You can also send data to the 
   //   method through it's parameters,
   //   although this method does NOT 
   //   contain any parameters.
   // You can call or invoke or run a method by using the name of the method.

   public static void sampleMethod() // The heading of the method
   { // begin marker for the code
      System.out.println("Hello, my name is sampleMethod()");
      System.out.println();
      System.out.println("I am a void method.");      
      System.out.println("I do not return a value (void)"); 
      System.out.println("I will leave now.\n");  
   } // end marker for the code
   

   // This method will be given a value when it is called.
   public static void sampleMethod2(String title)
   {
      System.out.println(title);
      System.out.println();
      System.out.println("This is a void method");      
      System.out.println("This does not return a value (void)");
      System.out.println("I will leave now.\n");  
      
   }
   
   
   // This method will be given 
   //   2 values when it is called.
   // It will also return a value. 
   public static int add(int x, int y)
   {
 
      int answer = a + b;
 
      return answer;
   }
   
   // This method will be given 
   //   1 value when it is called.
   // It will also return a value. 
   public static int abs(int a)
   {
      if (a >= 0)
      {
        return a;
      }
      return -a;
   }
   


   // This is where the action starts.
   //   When you click the Run button,
   //   1) Your code is saved.
   //   2) Your code is compiled or translated
   //        to what the machine can understand.
   //   3) Your machine code in method main 
   //        starts running. 

   public static void main (String [] args)
   {
       // calling methods by their name (invoking or running or executing)
      
 
      sampleMethod();

      sampleMethod2("Hello Java");



      Scanner input = new Scanner(System.in);

      System.out.println();
       
      System.out.print("Enter a value for a: ");
      int a = input.nextInt();

      System.out.print("Enter a value for b: ");
      int b = input.nextInt();

      int result = add(a,b);
 
       
      System.out.println();
      System.out.println(a + " + " + b + " is " + result);
   
   }
   
   
   
 } // end of class
 

Back to the Top

Sample Program - Return Methods



// Can you finish it for practice?

class Main 
{

  public static int max(int a, int b)
  {
      if (a > b)
          return a;
          
      return b;
  }

  public static int min(int a, int b)
  {

      return 0;
  }

  public static int add1(int x)
  {

      return 0;
  }
  
  public static boolean isPositive(int a)
  {
      if (a > 0)
          return true;
          
      return false;
  }

  public static boolean isNegative(int a)
  {
    
      return false;
  }

  public static boolean isEven(int a)
  {
      if (a % 2 == 0)
          return true;
          
      return false;
  }

  public static boolean isOdd(int a)
  {

      return false;
  }

  public static void main(String[] args) 
  {
    System.out.println("Writing Methods");
    System.out.println();

    System.out.println("max()");    System.out.println("max(5,8) is " + max(5,8));
    System.out.println("max(15,8) is " + max(15,8));  

    System.out.println();
    System.out.println("min()");    System.out.println("min(5,8) is " + min(5,8));

    System.out.println("min(15,8) is " + min(15,8));

    System.out.println();
    System.out.println("x and add1()"); 
    int x = 8;
    System.out.println("x is " + x);
    add1(x);
    add1(x);
    System.out.println("After adding 1 twice");  
    System.out.println("x is " + x);

    System.out.println();
    System.out.println("Positive?");
    x = 8;
    System.out.println(x + " is positive: " + isPositive(x));
    System.out.println();
    x = -8;
    System.out.println(x + " is positive: " + isPositive(x));

    System.out.println();
    System.out.println("Negative?");
    x = 8;
    System.out.println(x + " is negative: " + isNegative(x));
    System.out.println();
    x = -8;
    System.out.println(x + " is negative: " + isNegative(x));


    System.out.println();
    System.out.println("isEven?");
    x = 8;
    System.out.println(x + " is even: " + isEven(x));
    System.out.println();
    x = 9;
    System.out.println(x + " is even: " + isEven(x));

    System.out.println();
    System.out.println("isOdd?");
    x = 8;
    System.out.println(x + " is odd: " + isOdd(x));
    System.out.println();
    x = 9;
    System.out.println(x + " is odd: " + isOdd(x));


  } // end of method main

} // end of class Main



Back to the Top

Sample Class - Student



class Main {
  public static void main(String[] args) 
  {
    System.out.println("Hello Students!");
    System.out.println();

    Student s1 = new Student("Tom", "Baker", "12895");
    
    Student s2 = new Student("Sue", "Smith", "47329");

    System.out.println("============");
    s1.printStudentInfo();
    s1.setMp1Grade(98);
    s1.printStudentInfo();
    System.out.println("============");
    System.out.println();

    System.out.println("============");
    s2.printStudentInfo();
    s2.setMp1Grade(100);
    s2.printStudentInfo();
    System.out.println("============");
    System.out.println();

  } // end of method main
} // end of class Main

class Student 
{
  // instance variables
  // (properties, attributes,
  //  fields)
  private String firstName;
  private String lastName;
  private String id;
  private double mp1Grade;
  private double mp2Grade;
  private double examGrade;
  private double semesterGrade;

  // What is wrong with this?????
  // System.out.println("Welcome");


  // Student Constructor
  // Same name as the class
  // NO RETURN TYPE
  // used to initialize your
  // instance variables
  public Student(String fn, String ln, String id)
  {
    firstName = fn;
    lastName = ln;
    this.id = id;
    mp1Grade = -1;
    mp2Grade = -1;
    examGrade = -1;
    semesterGrade = -1;
  }

  // setter methods allow us to 
  // change the value of an 
  // instance variable
  // AKA Mutator methods
  // AKA Modifier methods
  public void setMp1Grade(double mp1Grade)
  {
    this.mp1Grade = mp1Grade;
  }

  public void setMp2Grade(double mp2)
  {
    this.mp2Grade = mp2;
  }

  // You should add more setter methods



  // getter method or accessor method
  // allows access from another class or this class
  public double getMp1Grade()
  {
    return mp1Grade;
  }

  public double getMp2Grade()
  {
    return mp2Grade;
  }


  public String getFullName()
  {
    return firstName + " " + lastName;
    // lastName + ", " + firstName;
  }

  public void printStudentInfo()
  {
    System.out.println(getFullName());

    if (mp1Grade == -1)
    {
      System.out.println("MP1: None");
    }
    else
    {
      System.out.println("MP1: " + mp1Grade);
      // or getMp1Grade()
    }

    if (mp2Grade == -1)
    {
      System.out.println("MP2: None");
    }
    else
    {
      System.out.println("MP2: " + mp2Grade);
      // or getMp2Grade()

    }

    // We should add getter methods fo
    // our other instance variables


    // We should check these as well    
    System.out.println("Exm: " + examGrade);    
    System.out.println("Sem: " + semesterGrade);       
  } // end of method

} // end of class Student



Back to the Top

Sample Class - Employee



// This import statement allows you to omit
// System. so that you can simply say
// out.println(...);    or   out.print(...);
import static java.lang.System.*;

// This import statement allows you to leave
// off the Math.sqrt(...) and just use
// sqrt(...)

import static java.lang.Math.*;

class Main {
  public static void main(String[] args) 
  {
    out.println("Pay Checks");
    out.println();

    // Create a new Employee object
    // Send the following data 
    // to the Constructor:
    // "67745", "Sue", "Smart"
    // NOTE: emp will hold the ???? ????
    //       of the Employee object
    Employee emp = new Employee("67745", "Sue", "Smart");

    // set the hours worked
    emp.setHoursWorked(42);

    // set the rate per hour
    emp.setRatePerHour(15.00);

    // Calculate the Pay
    emp.calculatePay();

    // print the pay check
    emp.printPayCheck();

    System.out.println("================");
    System.out.println("================");
    System.out.println("================");

    // A new Employee
    // Note that variable emp will now
    // hold the memory address of address
    // different employee
    // Why do we need an ID?????
    emp = new Employee("67245", "Bob", "Smith");

    // set the hours worked
    emp.setHoursWorked(30);

    // set the rate per hour
    emp.setRatePerHour(12.00);

    // Calculate the Pay
    emp.calculatePay();

    // print the pay check
    emp.printPayCheck();

   }
}

class Employee
{
    // instance variables
    // (attributes, properties, fields
    // global variables, records)
    private String id; 
    private String firstName;
    private String lastName;
    private double hoursWorked;
    private double ratePerHour;
    private double grossPay;

    // Constructor Employee
    // (Same name as the class)
    // Allows you to set the variables
    // (assign beginning values) 
    public Employee(String id, String fn, String ln)
    {
        this.id = id;
        this.firstName = fn;
        this.lastName = ln;

        // we will change these later
        hoursWorked = 0;
        ratePerHour = 0;
        grossPay = 0;
    }

    // Setter method or mutator method
    // This should store a new value for
    // hoursWorked
    public void setHoursWorked(double hw)
    {
       if (hw < 0)
       {
         hoursWorked = 0;  
       }
       hoursWorked = hw;
    }

    // Setter method or mutator method
    // This should store a new value for
    // ratePerHour
    public void setRatePerHour(double rate)
    {
       ratePerHour = rate;
    }

    // Calculates the amount of the grossPay
    public void calculatePay()
    {
       grossPay = hoursWorked * ratePerHour;
    }

    // This method gets the full name of 
    // the employee
    public String getFullName()
    {
      return firstName + " " + lastName;  
    }

    public void printPayCheck()
    {
      out.println("Name: " + getFullName());
      //out.println();
      out.println("Hours: " + hoursWorked);
      out.println("Rate:  " + ratePerHour);
      out.println("Pay:   " + grossPay);

      // or use format codes
      // %.2f will be replaced by the value of the 
      // variable and rounded to two decimal places.
      out.printf("Rate:  %.2f", ratePerHour);
      out.printf("Pay:   %.2f", grossPay);

    }

} // end of class Employee



Back to the Top

Sample Class - Cat



// Sample Program
// CatRunner.java and Cat.java

// FINISH ME
// Name: Your full name goes here


public class CatRunner // or Main for repl.it
{
  
 public static void main( String[] args )
 {
  System.out.println("Cat Years");
  System.out.println(); // prints a blank line
  System.out.println(); // prints a blank line

  // FINISH ME
  System.out.println("Sample Written by xxxxx xxxxx");
  System.out.println(); // prints a blank line
  System.out.println(); // prints a blank line
  
  
  // FINISH ME
  // Create or Instanstiate a Cat object.
  // c will receive the memory address of a
  // new Cat object.
  // Cat c means create a variable called c that 
  //   refers to a Cat object.
  Cat c = ??? ???( "Felix" );
  
  
  System.out.println( ?.getName() );
  System.out.println( ?.getAge() );
  
  System.out.println( ?.toString() );
  System.out.println( c );
  
  System.out.println("=====================");
  System.out.println( );
    
  
  // FINISH ME
  // Create another Cat object
  // g will receive the memory address of a
  // new Cat object (a different Cat object).
  // The values are sent (passed, mailed) to the 
  // Cat constructor inside Cat.java.
  // 
  ??? g = ??? ???(   "Bob",   3 );
  //                   |      |
  //                   |      |
  // public Cat(String n, int a)
  //
  // The Cat parameter variables will be created
  // and n receives "Bob"  and a receives 3
  
  System.out.println( ?.getName() );
  System.out.println( ?.getAge() );
  
  System.out.println( ?.toString() );
  System.out.println( g );
     
 } // end of method main
 
} end of class CatRunner
  




// The Cat class

// Remember, a class is a container that contains
// data and code.

// A class itself is the written part.
// It is a blue print or template or cookie cutter.

// When we new the class, we are creating an 
//    object in RAM memory.  This creating of the
//    object is known as instantiation.
//    We say we INSTANTIATE an object.

// The blue print is used
//    to lay out the storage and methods.

// The data is stored in variables.
// The code is stored in methods (or constructors)

public class Cat
{
   // These are instance variables.
   // The variables are always there in the object.
   // They hold our data.
   // Instance variables are also known as:
   // attributes, properties, fields, global variables
   // members
   private int age;
   private String name;
 
   
   // public Cat( String n ) is an 
   //     initialization CONSTRUCTOR.
   // It initializes your instance variables.
   // (gives beginning values to your instance variables) 
   // Cat( String n) is the signature.
   //
   // Argument "Bob" is sent or mailed to the 
   // Cat constructor.
   //              
   //       new Cat("Bob");
   //                 |      
   //                 |        
   public Cat( String n )  
   {
     // parameter variable n is created and 
     // receives the value of "Bob".
     // They create the box n, and then
     // they add n = "Bob";
     
     // assign to age the default value of 1
     // note that no value was sent for the age
     age = 1; 
     
     // We now store the value of n in the 
     // variable name. ("Bob" in this example)
     // i.e. The name variable receives the value
     //      stored in variable n.  So name
     //      receives "Bob".
     name = n;
     
     //   age      name
     // =======  =========
     // |  1  |  |  Bob  |
     // =======  =========
     
   } // end of Cat constructor
  
   
   // This is also a constructor.
   // It initializes your instance variables.
   
   // We say the constructors are overloaded.
   
   // You can have overloaded methods as well.
   
   // However, the signatures must differ.
   // Cat( String n, int a ) is the signature.
   
   // When we create an object, we say:
   //    new Cat(   "Bob",   3 );
   //                 |      |
   //                 |      |  
   public Cat( String n, int a )  
   {
     // variable n is created
     // n receives "Bob"
     // variable a is created
     // a receives 3

     // FINISH ME
     // init your instance variables
     age = ?;
     name = ?;

     // variable n is destroyed
     // variable a is destroyed
   } // end of Cat constructor
   
  
   public void increaseAgeByOne()
   {
     // FINISH ME
     // age = current value of Cat age + 1
     age = age + 1;
     
     // OR
     // age++;
     // age += 1;
   }
 
   
   // getter method (or accessor method)
   // It retrieves the value of the variable age
   // and returns it to the caller.
   public int getAge()    
   {
    // FINISH ME
    // This should return the Cat's age
     return ???;   // change me
   }
 

   // getter method (or accessor method)
   // It returns a String that holds the value
   // of the instance variable name.
   public String getName()    
   {
     // FINISH ME
     // This should return the Cat's name
     return ?????;   // change me
   }
 
   
   // a toString() method is special
   // It should return info about the 
   // instance variables.  Many IDE's 
   // will call this automatically at
   // break points.
   public String toString()    
   {
     // FINISH ME
     // This should return:
     // "Cat - " followed by the name of the Cat, 
     // a space, and the age of Cat
     return "Cat - " + name + " " + age;
     
     // OR return "Cat - " + getName() + " " + getAge();
     // OR return "Cat - " + this.name + " " + this.age;
     // 
   } // end of toString() method
   
   
} // end of class Cat

// Here is a picture of a Cat object.
// It is a like a box that holds
// variable values and methods that
// hold computer code (instructions).
/*

Cat c = new Cat("Bob");
   
//          new Cat("Bob");
//                    |      
//                    |        
// public Cat( String n )  

c  receives the memory address of the Cat
c  refers to the object 
c  tells us where in RAM memory to find the Cat

       c                   
  ===========               
  |  78235  |              
  ===========               


Location in RAM memory: 78235 (memory address)
-----------------------------------
|    age      name                |
|  =======  =========             |
|  |  1  |  |  Bob  |             |
|  =======  =========             |
|                                 |
|  public Cat( String n )         |
|  ==========================     |
|  |   code not shown       |     |
|  ==========================     |
|                                 |
|  public Cat( String n, int a )  |
|  ==========================     |
|  |   code not shown       |     |
|  ==========================     |
|                                 |
|  Other methods not shown        |
|                                 |
-----------------------------------

*/


Sample Class Help - Math

import static java.lang.System.*; public class Main // HelpMath { public static void main(String[] args) { out.println("The Math Class"); out.println(); out.println(); /* out.println("Math Methods"); out.println(); out.println("abs() returns the absolute value of a given number"); out.println("sqrt() returns the square root of a given number as a double"); out.println("min() returns the smaller of two given numbers"); out.println("max() returns the larger of two given numbers"); out.println("floor() returns the given number rounded down"); out.println("ceil() returns the given number rounded up"); out.println("round() returns the given number rounded to the closest int"); out.println(); out.println(); */ out.println("Math.abs(?)"); out.println("=============="); out.println("Math.abs(24) is " + Math.abs(24)); out.println("Math.abs(-24) is " + Math.abs(-24)); out.println("Math.abs(7) is " + Math.abs(7)); out.println("Math.abs(-7) is " + Math.abs(-7)); out.println("Math.abs(-7.4) is " + Math.abs(-7.4)); out.println("Math.abs(-7.5) is " + Math.abs(-7.5)); out.println("Math.abs(-7.7) is " + Math.abs(-7.7)); out.println(); out.println("Math.sqrt(?)"); out.println("=============="); out.println("Math.sqrt(0) is " + Math.sqrt(0)); out.println("Math.sqrt(9) is " + Math.sqrt(9)); out.println("Math.sqrt(12) is " + Math.sqrt(12)); out.println("Math.sqrt(16) is " + Math.sqrt(16)); out.println("Math.sqrt(20) is " + Math.sqrt(20)); out.println("Math.sqrt(25) is " + Math.sqrt(25)); out.println(); out.println("Math.min(?, ?) (returns the smaller number)"); out.println("=============="); out.println("Math.min(2, 3) is " + Math.min(2,3)); out.println("Math.min(-3, 8) is " + Math.min(-3, 8)); out.println("Math.min(13, 7) is " + Math.min(13, 7)); out.println("Math.min(1.2, 2) is " + Math.min(1.2, 2)); out.println("Math.min(20, 3.14) is " + Math.min(20, 3.14)); out.println("Math.min(25, 27.7) is " + Math.min(25, 27.5)); out.println(); out.println("Math.max(?, ?) (returns the larger number)"); out.println("=============="); out.println("Math.max(2, 3) is " + Math.max(2,3)); out.println("Math.max(-3, 8) is " + Math.max(-3, 8)); out.println("Math.max(13, 7) is " + Math.max(13, 7)); out.println("Math.max(1.2, 2) is " + Math.max(1.2, 2)); out.println("Math.max(20, 3.14) is " + Math.max(20, 3.14)); out.println("Math.max(25, 27.5) is " + Math.max(25, 27.5)); out.println(); out.println("Math.floor(?) (rounds down)"); out.println("=============="); out.println("Math.floor(2) is " + Math.floor(2)); out.println("Math.floor(-3.8) is " + Math.floor(-3.8)); out.println("Math.floor(-3.5) is " + Math.floor(-3.5)); out.println("Math.floor(13.7) is " + Math.floor(13.7)); out.println("Math.floor(1.2) is " + Math.floor(1.2)); out.println("Math.floor(3.001) is " + Math.floor(3.001)); out.println("Math.floor(27.5) is " + Math.floor(27.5)); out.println(); out.println("Math.ceil(?) (rounds up)"); out.println("=============="); out.println("Math.ceil(2) is " + Math.ceil(2)); out.println("Math.ceil(-3.8) is " + Math.ceil(-3.8)); out.println("Math.ceil(-3.5) is " + Math.ceil(-3.5)); out.println("Math.ceil(13.7) is " + Math.ceil(13.7)); out.println("Math.ceil(1.2) is " + Math.ceil(1.2)); out.println("Math.ceil(3.001) is " + Math.ceil(3.001)); out.println("Math.ceil(27.5) is " + Math.ceil(27.5)); out.println(); out.println("Math.round(?) (rounds to nearest int)"); out.println("=============="); out.println("Math.round(2) is " + Math.round(2)); out.println("Math.round(-3.8) is " + Math.round(-3.8)); out.println("Math.round(-3.5) is " + Math.round(-3.5)); out.println("Math.round(13.7) is " + Math.round(13.7)); out.println("Math.round(1.2) is " + Math.round(1.2)); out.println("Math.round(3.001) is " + Math.round(3.001)); out.println("Math.round(27.5) is " + Math.round(27.5)); out.println(); out.println("Math.pow(?, ?) (raises to a power)"); out.println("=============="); out.println("Math.pow(2, 3) is " + Math.pow(2, 3)); out.println("Math.pow(2, 4) is " + Math.pow(2, 4)); out.println("Math.pow(2, 5) is " + Math.pow(2, 5)); out.println("Math.pow(10, 2) is " + Math.pow(10, 2)); out.println("Math.pow(2.2, 3) is " + Math.pow(2.2, 3)); out.println(); } // end of main method } // end of class HelpMath

Sample Class Help - Methods

import static java.lang.System.*; public class Main // HelpMethods { // Method add will receive two values. // The first value will be put in variable a. // The second value will be put in variable b. // a and b are called parameters. // They are local to this method only. // The method creates the variables and // then assigns the incoming values to the // variables. // For example: add(7, 8) would // create variable a and assign it 7. // create variable b and assign it 8. // The method would return 15. // The variables will be destroyed when // the method ends. public static int add(int a, int b) { return a + b; } public static int mult(int a, int b) { return a * b; } public static int go(int a, int b, int c, int d) { return add(a,b) + mult(c,d); } public static void main(String[] args) { out.println("Help with Methods"); out.println(); out.println(); // Calling method add from above out.println("Calling method add"); out.println("=================="); // 2 is sent to variable a // 4 is sent to variable b out.println("add(2, 4) is " + add(2, 4)); // -2 is sent to variable a // 8 is sent to variable b out.println("add(-2, 8) is " + add(-2, 8)); out.println(); // Calling method mult from above out.println("Calling method mult"); out.println("=================="); out.println("mult(2, 4) is " + mult(2, 4)); out.println("mult(-2, 8) is " + mult(-2, 8)); out.println(); // Calling method go from above out.println("Calling method go"); out.println("=================="); out.println("go(2, 4, 6, 8) is " + go(2, 4, 6, 8)); out.println("go(-2, 8, 4, 5) is " + go(-2, 8, 4, 5)); out.println(); } // end of main method } // end of class HelpMethods

Back to the Top