Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
AP Computer Science A is an introductory college-level computer science course. Students cultivate their understanding of coding through analyzing, writing, and testing code as they explore concepts like modularity, variables, and control structures.
This website is written by Mr. Cheng, a high school computer science teacher and adjunct professor. He can be reached at mcheng @ appinventor.net
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
Represent branching logical processes by using conditional statements.
A multi-way selection is written when there are a series of conditions with different statements for each condition. Multi-way selection is performed using if-else-if statements such that exactly one section of code is executed based on the first condition that evaluates to true.
For String class:
a. Create String objects.
b. Call String methods.
String objects can be created by using string literals or by calling the String class constructor.
String objects are immutable, meaning that String methods do not change the String object.
String objects can be concatenated using the + or += operator, resulting in a new String object.
Primitive values can be concatenated with a String object. This causes implicit conversion of the values to String objects.
Escape sequences start with a \ and have a special meaning in Java. Escape sequences used in this course include \”, \, and \n.
Call non-static non-void methods with or without parameters.
Non-void methods return a value that is the same type as the return type in the signature. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
1.3.C.2 The arithmetic operators consist of addition +, subtraction -, multiplication *, division /, and remainder %. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at leaset one double value will evaluate to a double value.
Exclusion Statement: Expressions that result in special double values (e.g. infinities and NaN) are outside the scope of the AP Computer Science A course and exam.
1.3.A Develop code to generate output and determine the result that would be displayed.
1.3.A.1 System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.
1.3.B Develop code to utilize string literals and determine the result of using string literals.
1.3.B.1 A literal is the code representation of a fixed value.
1.3.B.2 A string literal is a sequence of characters enclosed in double quotes.
1.3.B.3 Escape sequences are special sequences of characters that can be included in a string. They start with a \ and have a special meaning in Java. Escape sequences used in this course include double quote \", backslash \\, and newline \n.
1.3.C Develop code for arithmetic expressions and determine the result of these expressions
1.3.C.1 Arithmetic expressions, which consist of numeric values, variables and operators, include expressions of type int and double.
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
Traverse the elements in a 1D array object using an enhanced for loop.
An enhanced for loop header includes a variable, referred to as the enhanced for loop variable.
For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.
Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
Program code written using an enhanced for loop to traverse and access elements in an array can be rewritten using an indexed for loop or a while loop.
When multiple classes contain common attributes and behaviors, programmers create a new class containing the shared attributes and behaviors forming a hierarchy. Modifications made at the highest level of the hierarchy apply to the subclasses.
Create an inheritance relationship from a subclass to the superclass.
A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass.
Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without repeating these in the code.
Extending a subclass from a superclass creates an “is-a” relationship from the subclass to the superclass.
The keyword extends is used to establish an inheritance relationship between a subclass and a superclass. A class can extend only one superclass.
Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
Designate access and visibility constraints to classes, data, constructors, and methods.
The keywords public and private affect the access of classes, data, constructors, and methods.
The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
Classes are designated public.
Access to attributes should be kept internal to the class. Therefore, instance variables are designated as private.
Constructors are designated public.
Access to behaviors can be internal or external to the class. Therefore, methods can be designated as either public or private.
When multiple classes contain common attributes and behaviors, programmers create a new class containing the shared attributes and behaviors forming a hierarchy. Modifications made at the highest level of the hierarchy apply to the subclasses.
Designate private visibility of instance variables to encapsulate the attributes of an object.
Data encapsulation is a technique in which the implementation details of a class are kept hidden from the user.
When designing a class, programmers make decisions about what data to make accessible and modifiable from an external class. Data can be either accessible or modifiable, or it can be both or neither.
Instance variables are encapsulated by using the private access modifier.
The provided accessor and mutator methods in a class allow client code to use and modify data.
Some objects or concepts are so frequently represented that programmers can draw upon existing code that has already been tested, enabling them to write solutions more quickly and with a greater degree of confidence.
Explain the relationship between a class and an object.
An object is a specific instance of a class with defined attributes.
A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
For algorithms in the context of a particular specification that requires the use of ArrayList traversals:
§ Identify standard algorithms.
§ Modify standard algorithms.
§ Develop an algorithm.
There are standard ArrayList algorithms that utilize traversals to:
§ Insert elements § Delete elements § Apply the same standard algorithms that are used with 1D arrays
Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously.
Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
Define behaviors of an object through void methods with or without parameters written in a class.
A void method does not return a value. Its header contains the keyword void before the method name.
A mutator (modifier) method is often a void method that changes the values of instance variables or static variables.
While programs are typically designed to achieve a specific purpose, they may have unintended consequences.
Explain the ethical and social implications of computing systems.
System reliability is limited. Programmers should make an effort to maximize system reliability.
Legal issues and intellectual property concerns arise when creating programs.
The creation of programs has impacts on society, economies, and culture. These impacts can be beneficial and/or harmful.
Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
Define behaviors of an object through non-void methods with parameters written in a class.
Methods can only access the private data and methods of a parameter that is a reference to an object when the parameter is the same type as the method’s enclosing class.
Non-void methods with parameters receive values through parameters, use those values, and return a computed value of the specified type.
It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification.
When an actual parameter is a primitive value, the formal parameter is initialized with a copy of that value. Changes to the formal parameter have no effect on the corresponding actual parameter.
When an actual parameter is a reference to an object, the formal parameter is initialized with a copy of that reference, not a copy of the object. If the reference is to a mutable object, the method or constructor can use this reference to alter the state of the object.
Passing a reference parameter results in the formal parameter and the actual parameter being aliases. They both refer to the same object.
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
Compute statement execution counts and informal run-time comparison of iterative statements.
A statement execution count indicates the number of times a statement is executed by the program.
The way variables and operators are sequenced and combined in an expression determines the computed result.
Evaluate what is stored in a variable as a result of an expression with an assignment statement.
Compound assignment operators (+=, −=, *=, /=, %=) can be used in place of the assignment operator.
The increment operator (++) and decrement operator (−−) are used to add 1 or subtract 1 from the stored value of a variable or an array element. The new value is assigned to the variable or array element.
Exclusion Statement: The use of increment and decrement operators in prefix form (i.e., ++x) and inside other expressions (i.e., arr[x++]) is outside the scope of this course and the AP Exam.
When multiple classes contain common attributes and behaviors, programmers create a new class containing the shared attributes and behaviors forming a hierarchy. Modifications made at the highest level of the hierarchy apply to the subclasses.
Create an inheritance relationship from a subclass to the superclass.
Constructors are not inherited.
The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters.
The actual parameters passed in the call to the superclass constructor provide values that the constructor can use to initialize the object’s instance variables.
When a subclass’s constructor does not explicitly call a superclass’s constructor using super, Java inserts a call to the superclass’s no-argument constructor.
Regardless of whether the superclass constructor is called implicitly or explicitly, the process of calling superclass constructors continues until the Object constructor is called. At this point, all of the constructors within the hierarchy execute beginning with the Object constructor.
To find specific solutions to generalizable problems, programmers include variables in their code so that the same algorithm runs using different input values.
Evaluate object reference expressions that use the keyword this.
Within a non-static method or a constructor, the keyword this is a reference to the current object—the object whose method or constructor is being called.
The keyword this can be used to pass the current object as an actual parameter in a method call.
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
Apply recursive search algorithms to information in String, 1D array, or ArrayList objects.
Data must be in sorted order to use the binary search algorithm.
The binary search algorithm starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each iteration until the desired value is found or all elements have been eliminated.
Binary search can be more efficient than sequential/linear search.
Search algorithms other than sequential/linear and binary search are outside the scope of the course and AP Exam.
The binary search algorithm can be written either iteratively or recursively.
Apply recursive algorithms to sort elements of array or ArrayList objects.
Merge sort is a recursive sorting algorithm that can be used to sort elements in an array or ArrayList.
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
Represent collections of related object reference data using ArrayList objects.
An ArrayList object is mutable and contains object references.
The ArrayList constructor ArrayList() constructs an empty list.
Java allows the generic type ArrayList, where the generic type E specifies the type of the elements.
When ArrayList is specified, the types of the reference parameters and return type when using the methods are type E.
ArrayList is preferred over ArrayList because it allows the compiler to find errors that would otherwise be found at run-time.
The way variables and operators are sequenced and combined in an expression determines the computed result.
Evaluate arithmetic expressions that use casting.
The casting operators (int) and (double) can be used to create a temporary value converted to a different data type.
Casting a double value to an int causes the digits to the right of the decimal point to be truncated.
Some programming code causes int values to be automatically cast (widened) to double values.
Values of type double can be rounded to the nearest integer by (int)(x + 0.5) or (int)(x – 0.5) for negative numbers.
Integer values in Java are represented by values of type int, which are stored using a finite amount (4 bytes) of memory. Therefore, an int value must be in the range from Integer.MIN_VALUE to Integer.MAX_ VALUE inclusive.
If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. This could result in an incorrect value within the allowed range.
The way variables and operators are sequenced and combined in an expression determines the computed result.
Compare and contrast equivalent Boolean expressions.
De Morgan’s Laws can be applied to Boolean expressions.
Truth tables can be used to prove Boolean identities.
Equivalent Boolean expressions will evaluate to the same value in all cases.
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
Represent nested iterative processes.
Nested iteration statements are iteration statements that appear in the body of another iteration statement.
When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue.
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
Traverse the elements in a 1D array.
Iteration statements can be used to access all the elements in an array. This is called traversing the array.
Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
Since the indices for an array start at 0 and end at the number of elements − 1, “off by one” errors are easy to make when traversing an array, resulting in an ArrayIndexOutOfBoundsException being thrown.
Identify, using its signature, the correct constructor being called.
A signature consists of the constructor name and the parameter list.
The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names. These are often referred to as formal parameters.
A parameter is a value that is passed into a constructor. These are often referred to as actual parameters.
Constructors are said to be overloaded when there are multiple constructors with the same name but a different signature.
The actual parameters passed to a constructor must be compatible with the types identified in the formal parameter list.
Parameters are passed using call by value. Call by value initializes the formal parameters with copies of the actual parameters.
For creating objects:
a. Create objects by calling constructors without parameters.
b. Create objects by calling constructors with parameters.
Every object is created using the keyword new followed by a call to one of the class’s constructors.
A class contains constructors that are invoked to create objects. They have the same name as the class.
Existing classes and class libraries can be utilized as appropriate to create objects.
Parameters allow values to be passed to the constructor to establish the initial state of the object.
To find specific solutions to generalizable problems, programmers include variables in their code so that the same algorithm runs using different input values.
Define variables of the correct types to represent reference data.
The keyword null is a special value used to indicate that a reference is not associated with any object.
The memory associated with a variable of a reference type holds an object reference value or, if there is no object, null. This value is the memory address of the referenced object.
Call static methods.
Static methods are called using the dot operator along with the class name unless they are defined in the enclosing class.
The way variables and operators are sequenced and combined in an expression determines the computed result.
Evaluate expressions that use the Math class methods.
The Math class is part of the java.lang package.
The Math class contains only static methods.
The following static Math methods—including what they do and when they are used—are part of the Java Quick Reference:
int abs(int x) — Returns the absolute value of an int value
double abs(double x) — Returns the absolute value of a double value
double pow(double base, double exponent) — Returns the value of the first parameter raised to the power of the second parameter
double sqrt(double x) — Returns the positive square root of a double value
double random()— Returns a double value greater than or equal to 0.0 and less than 1.0
The values returned from Math.random can be manipulated to produce a random int or double in a defined range.
a. Create String objects.
b. Call String methods.
Application program interfaces (APIs) and libraries simplify complex programming tasks.
Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class.
Classes in the APIs and libraries are grouped into packages.
The String class is part of the java.lang package. Classes in the java.lang package are available by default.
A String object has index values from 0 to length – 1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.
A String object can be concatenated with an object reference, which implicitly calls the referenced object’s toString method.
The following String methods and constructors—including what they do and when they are used—are part of the Java Quick Reference:
String(String str) — Constructs a new String object that represents the same sequence of characters as str
int length()— Returns the number of characters in a String object
String substring(int from, int to)— Returns the substring beginning at index from and ending at index to -1
String substring(int from) — Returns substring(from, length())
int indexOf(String str) — Returns the index of the first occurrence of str; returns -1 if not found
boolean equals(String other) — Returns true if this is equal to other; returns false otherwise
int compareTo(String other) — Returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other
A string identical to the single element substring at position index can be created by calling substring(index, index + 1).
Iteration statements change the flow of control by repeating a set of statements zero or more times until a condition is met.
In loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the expression evaluates to false, whereupon the iteration ceases.
A loop is an infinite loop when the Boolean expression always evaluates to true.
If the Boolean expression evaluates to false initially, the loop body is not executed at all.
Executing a return statement inside an iteration statement will halt the loop and exit the method or constructor.
For algorithms in the context of a particular specification that does not require the use of traversals:
Identify standard algorithms.
Modify standard algorithms.
Develop an algorithm.
There are standard algorithms to:
Identify if an integer is or is not evenly divisible by another integer
Identify the individual digits in an integer
Determine the frequency with which a specific criterion is met
There are standard algorithms to:
Determine a minimum or maximum value
Compute a sum, average, or mode
Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList.
Compute statement execution counts and informal run-time comparison of sorting algorithms.
Informal run-time comparisons of program code segments can be made using statement execution counts.
For algorithms in the context of a particular specification that involves String objects:
Identify standard algorithms.
Modify standard algorithms.
Develop an algorithm.
There are standard algorithms that utilize String traversals to:
Find if one or more substrings has a particular property
Determine the number of substrings that meet specific criteria
Create a new string with the characters reversed
Define reference variables of a superclass to be assigned to an object of a subclass in the same hierarchy.
When a class S “is-a” class T, T is referred to as a superclass, and S is referred to as a subclass.
If S is a subclass of T, then assigning an object of type S to a reference of type T facilitates polymorphism.
If S is a subclass of T, then a reference of type T can be used to refer to an object of type T or S.
Declaring references of type T, when S is a subclass of T, is useful in the following declarations:
§ Formal method parameters § arrays — T[] var ArrayList<T> var
Call non-static void methods without parameters.
An object’s behavior refers to what the object can do (or what can be done to it) and is defined by methods.
Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
A method signature for a method without parameters consists of the method name and an empty parameter list.
A method or constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the method or constructor before continuing. Once the last statement in the method or constructor has executed or a return statement is executed, flow of control is returned to the point immediately following where the method or constructor was called.
Non-static methods are called through objects of the class.
The dot operator is used along with the object name to call non-static methods.
Void methods do not have return values and are therefore not called as part of an expression.
Using a null reference to call a method or access an instance variable causes a NullPointerException to be thrown.
Define behaviors of a class through static methods.
Static methods are associated with the class, not objects of the class.
Static methods include the keyword static in the header before the method name.
Static methods cannot access or change the values of instance variables.
Static methods can access or change the values of static variables.
Static methods do not have a this reference and are unable to use the class’s instance variables or call non-static methods.
Define the static variables that belong to the class.
Static variables belong to the class, with all objects of a class sharing a single static variable.
Static variables can be designated as either public or private and are designated with the static keyword before the variable type.
Static variables are used with the class name and the dot operator, since they are associated with a class, not objects of a class.
Call non-static void methods with parameters.
A method signature for a method with parameters consists of the method name and the ordered list of parameter types.
Values provided in the parameter list need to correspond to the order and type in the method signature.
Methods are said to be overloaded when there are multiple methods with the same name but a different signature.
An object’s state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This creates a “has-a” relationship between the object and its instance variables.
Constructors are used to set the initial state of an object, which should include initial values for all instance variables.
Constructor parameters are local variables to the constructor and provide data to initialize instance variables.
When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable is not an alias of the original object, and methods are prevented from modifying the state of the original object.
When no constructor is written, Java provides a no-argument constructor, and the instance variables are set to default values.
Represent collections of related primitive or object reference data using one- dimensional (1D) array objects.
The use of array objects allows multiple related items to be represented using a single variable.
The size of an array is established at the time of creation and cannot be changed.
Arrays can store either primitive data or object reference data.
When an array is created using the keyword new, all of its elements are initialized with a specific value based on the type of elements:
Elements of type int are initialized to 0
Elements of type double are initialized to 0.0
Elements of type boolean are initialized
Elements of a reference type are initialized to the reference value null. No objects are automatically created
Initializer lists can be used to create and initialize arrays.
Square brackets ([ ]) are used to access and modify an element in a 1D array using an index.
The valid index values for an array are 0 through one less than the number of elements in the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException being thrown.
A two-way selection is written when there are two sets of statements— one to be executed when the Boolean condition is true, and another set for when the Boolean condition is false. In this case, the body of the “if” is executed when the Boolean condition is true, and the body of the “else” is executed when the Boolean condition is false.
Call Object class methods through inheritance.
The Object class is the superclass of all other classes in Java.
The Object class is part of the java.lang package
The following Object class methods and constructors—including what they do and when they are used—are part of the Java Quick Reference:
boolean equals(Object other)
String toString()
Subclasses of Object often override the equals and toString methods with class- specific implementations.
A recursive method is a method that calls itself.
Recursive methods contain at least one base case, which halts the recursion, and at least one recursive call.
Each recursive call has its own set of local variables, including the formal parameters.
Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop.
Any recursive solution can be replicated through the use of an iterative approach.
Exclusion Statement: Writing recursive program code is outside the scope of the course and AP Exam.
Recursion can be used to traverse String, array, and ArrayList objects.
There are standard algorithms for searching.
Sequential/linear search algorithms check each element in order until the desired value is found or all elements in the array or ArrayList have been checked.
When using the computer, personal privacy is at risk. Programmers should attempt to safeguard personal privacy.
Computer use and the creation of programs have an impact on personal security. These impacts can be beneficial and/or harmful.
Create an inheritance relationship from a subclass to the superclass.
The keyword super can be used to call a superclass’s constructors and methods.
The superclass method can be called in a subclass by using the keyword super with the method name and passing appropriate parameters.
Define behaviors of an object through non-void methods without parameters written in a class.
An accessor method allows other objects to obtain the value of instance variables or static variables.
A non-void method returns a single value. Its header includes the return type in place of the keyword void.
In non-void methods, a return expression compatible with the return type is evaluated, and a copy of that value is returned. This is referred to as “return by value.”
When the return expression is a reference to an object, a copy of that reference is returned, not a copy of the object.
The return keyword is used to return the flow of control to the point immediately following where the method or constructor was called.
The toString method is an overridden method that is included in classes to provide a description of a specific object. It generally includes what values are stored in the instance data of the object.
If System.out.print or System.out. println is passed an object, that object’s toString method is called, and the returned string is printed.
Primitive values and reference values can be compared using relational operators (i.e., == and !=).
Arithmetic expression values can be compared using relational operators (i.e., <, >, <=, >=).
An expression involving relational operators evaluates to a Boolean value.
1.2.B.2 A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type. A variable of a primitive type holds a primitive value from that type.
1.A Determine an appropriate program design to solve a problem or accomplish a task
2.A Write program code to implement an algorithm
1.2.A Identify the most appropriate data type category for a particular specification.
1.2.A.1 A data type is a set of values and a corresponding set of operations on those values. Data types can be categorized as either primitive or reference.
1.2.A.2 The primitive data types in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
1.2.A.3 A reference type is used to define objects that are not primitive types.
1.2.B Develop code to declare variables to store numbers and Boolean values.
1.2.B.1 The three primitive data types used in this course are int, double, and boolean. An int value is an integer. A double value is a real number. A boolean value is either true or false.
Exclusion Statement: The other five primitive data types (long, short, byte, float and char) are outside the scope of the AP Computer Science A course and exam.
1.1.C.2 A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
1.1.C.3 A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
1.1.C.4 An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the program's execution.
1.A Determine an appropriate program design to solve a problem or accomplish a task
1.1.A. Represent patterns and algorithms found in everyday life using written language or diagrams.
1.1.A.1 Algorithms define step-by-step processes to follow when completing a task or solving a program. These algorithms can be represented using written language or diagrams.
1.1.A.2 Sequencing defines an order for when steps in a process are completed. Steps in a process ar ecompleted one at a time.
1.1.B Explain the code compilation and execution process.
1.1.B.1 Code can be written in any text editor; however an integrated development environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile and run code.
1.1.B.2 A compiler checks code for some errors. Error detectable by the compiler need to be fixed before the program be run.
1.1.C Identify types of programming errors
1.1.C.1 A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler.
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
Represent branching logical processes by using conditional statements.
Conditional statements interrupt the sequential execution of statements.
if statements affect the flow of control by executing different statements based on the value of a Boolean expression.
A one-way selection (if statement) is written when there is a set of statements to execute under a certain condition. In this case, the body is executed only when the Boolean condition
is true.
To find specific solutions to generalizable problems, programmers include variables in their code so that the same algorithm runs using different input values.
For wrapper classes:
a. Create Integer objects.
b. Call Integer methods.
c. Create Double objects.
d. Call Double methods.
The Integer class and Double class are part of the java.lang package.
The following Integer methods and constructors—including what they do and when they are used—are part of the Java Quick Reference:
Integer(int value) — Constructs a new Integer object that represents the specified int value
Integer.MIN_VALUE— The minimum value represented by an int or Integer
Integer.MAX_VALUE— The maximum value represented by an int or Integer
int intValue()— Returns the value of this Integer as an int
The following Double methods and constructors—including what they do and when they are used—are part of the Java Quick Reference:
Double(double value) — Constructs a new Double object that represents the specified double value
double doubleValue()— Returns the value of this Double as a double
Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double.
The Java compiler applies autoboxing when a primitive value is:
Passed as a parameter to a method that expects an object of the corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double.
The Java compiler applies unboxing when a wrapper class object is:
Passed as a parameter to a method that expects a value of the corresponding primitive type.
Assigned to a variable of the corresponding primitive type.
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
Represent branching logical processes by using nested conditional statements.
Nested if statements consist of if statements within if statements.
The way variables and operators are sequenced and combined in an expression determines the computed result.
Evaluate compound Boolean expressions in program code.
Logical operators !(not), &&(and), and ||(or) are used with Boolean values. This represents the order these operators will be evaluated.
An expression involving logical operators evaluates to a Boolean value.
When the result of a logical expression using && or || can be determined by evaluating only the first Boolean operand, the second is not evaluated. This is known as short-circuited evaluation.
Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
Describe the functionality and use of program code through comments.
Comments are ignored by the compiler and are not executed when the program is run.
Three types of comments in Java include /* /, which generates a block of comments, //, which generates a comment on one line, and /* */, which are Javadoc comments and are used to create API documentation.
A precondition is a condition that must be true just prior to the execution of a section of program code in order for the method to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
A postcondition is a condition that must always be true after the execution of a section of program code. Postconditions describe the outcome of the execution in terms of what is being returned or the state of an object.
Programmers write method code to satisfy the postconditions when preconditions are met.
To find specific solutions to generalizable problems, programmers include variables in their code so that the same algorithm runs using different input values.
Explain where variables can be used in the program code.
Local variables can be declared in the body of constructors and methods. These variables may only be used within the constructor or method and cannot be declared to be public or private.
When there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable.
Formal parameters and variables declared in a method or constructor can only be used within that method or constructor.
Through method decomposition, a programmer breaks down a large problem into smaller subproblems by creating methods to solve each individual subproblem.
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
Represent collections of related primitive or object reference data using two-dimensional (2D) array objects.
2D arrays are stored as arrays of arrays. Therefore, the way 2D arrays are created and indexed is similar to 1D array objects.
Exclusion Statement: 2D array objects that are not rectangular are outside the scope of the course and AP Exam.
For the purposes of the exam, when accessing the element at arr[first][second], the first index is used for rows, the second index is used for columns.
The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays.
The square brackets [row][col] are used to access and modify an element in a 2D array.
“Row-major order” refers to an ordering of 2D array elements where traversal occurs across each row, while “column-major order” traversal occurs down each column.
When multiple classes contain common attributes and behaviors, programmers create a new class containing the shared attributes and behaviors forming a hierarchy. Modifications made at the highest level of the hierarchy apply to the subclasses.
Create an inheritance relationship from a subclass to the superclass.
Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass.
Any method that is called must be defined within its own class or its superclass.
A subclass is usually designed to have modified (overridden) or additional methods or instance variables.
A subclass will inherit all public methods from the superclass; these methods remain public in the subclass.
The way variables and operators are sequenced and combined in an expression determines the computed result.
Compare object references using Boolean expressions in program code.
Two object references are considered aliases when they both reference the same object.
Object reference values can be compared, using == and !=, to identify aliases.
A reference value can be compared with null, using == or !=, to determine if the reference actually references an object.
Often classes have their own equals method, which can be used to determine whether two objects of the class are equivalent.
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
For 2D array objects:
Traverse using nested for loops.
Traverse using nested enhanced for loops.
Nested iteration statements are used to traverse and access all elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops and enhanced for loops is similar to 1D array objects.
Nested iteration statements can be written to traverse the 2D array in “row-major order” or “column-major order.”
The outer loop of a nested enhanced for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array. The inner loop traverses a single row. Therefore, the inner enhanced for
loop variable must be the same type as the elements stored in the 1D array.
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
For algorithms in the context of a particular specification that requires the use of 2D array traversals:
§ Identify standard algorithms.
§ Modify standard algorithms.
§ Develop an algorithm.
When applying sequential/linear search algorithms to 2D arrays, each row must be accessed then sequential/linear search applied to each row of a 2D array.
All standard 1D array algorithms can be applied to 2D array objects.
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
Represent collections of related object reference data using ArrayList objects.
The ArrayList class is part of the java. util package. An import statement can be used to make this class available for use in the program.
The following ArrayList methods— including what they do and when they are used—are part of the Java Quick Reference:
int size()-Returnsthenumberof elements in the list
boolean add(E obj)-Appends obj to end of list; returns true
void add(int index, E obj)- Inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size
E get(int index)-Returns the element at position index in the list
E set(int index, E obj)— Replaces the element at position index with obj; returns the element formerly at position index
E remove(int index)—Removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index
§ Identify standard algorithms.
§ Modify standard algorithms.
§ Develop an algorithm.
There are standard algorithms that utilize array traversals to:
Determine a minimum or maximum value
Compute a sum, average, or mode
Determine if at least one element has a particular property
Determine if all elements have a particular property
Access all consecutive pairs of elements
Determine the presence or absence of duplicate elements
Determine the number of elements meeting specific criteria
There are standard array algorithms that utilize traversals to:
Shift or rotate elements left or right § Reverse the order of the elements
public class S1Problem1 {
public static void main(String[] args) {
System.out.println("Problem 1");
}
}public class S1Problem2 {
public static void main(String[] args) {
System.out.println("Problem 2");
}
}public class S1Problem3 {
public static void main(String[] args) {
System.out.println("Problem 3");
}
}public class S1Problem4 {
public static void main(String[] args) {
System.out.println("Problem 4");
}
}public class S1Problem5 {
public static void main(String[] args) {
System.out.println("Problem 5");
}
}public class S1Problem6 {
public static void main(String[] args) {
System.out.println("Problem 6");
}
}public class S1Problem7 {
public static void main(String[] args) {
System.out.println("Problem 7");
}
}public class S1Problem8 {
public static void main(String[] args) {
System.out.println("Problem 8");
}
}public class S1Problem7 {
public static void main(String[] args) {
System.out.println("Problem 9");
}
}public class S1Problem7 {
public static void main(String[] args) {
System.out.println("Problem 10");
}
}import java.util.*;
public class CastingDemo {
public static void main(String[] args) {
System.out.println("Casting Demo");
// Example 1
// Example 2
// Example 3
// Example 4
// Example 5
// Example 6
// Example 7
// Example 8
}
}public class CompoundOperator {
public static void main(String[] args) {
int x = 10;
System.out.println("Initial value of x: " + x);
// addition
// subtraction
// multiplication
// division
// modulus
}
}
Programmers incorporate iteration and selection into code as a way of providing instructions for the computer to process each of the many possible input values.
Represent iterative processes using a for loop.
There are three parts in a for loop header: the initialization, the Boolean expression, and the increment. The increment statement can also be a decrement statement.
In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The variable being initialized is referred to as a loop control variable.
In each iteration of a for loop, the increment statement is executed after the entire loop body is executed and before the Boolean expression is evaluated again.
A for loop can be rewritten into an equivalent while loop and vice versa.
“Off by one” errors occur when the iteration statement loops one time too many or one time too few.
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
For ArrayList objects:
a. Traverse using a for or while loop
b. Traverse using an enhanced for loop
Iteration statements can be used to access all the elements in an ArrayList. This is called traversing the ArrayList.
Deleting elements during a traversal of an ArrayList requires using special techniques to avoid skipping elements.
Since the indices for an ArrayList start at 0 and end at the number of elements − 1, accessing an index value outside of this range will result in an ArrayIndexOutOfBoundsException being thrown.
Changing the size of an ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException being thrown. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.
import java.util.*;
public class S3Problem1 {
public static void main(String[] args) {
System.out.println("Problem 1");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S3Problem2 {
public static void main(String[] args) {
System.out.println("Problem 2");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S3Problem3 {
public static void main(String[] args) {
System.out.println("Problem 3");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S3Problem4 {
public static void main(String[] args) {
System.out.println("Problem 4");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S3Problem5 {
public static void main(String[] args) {
System.out.println("Problem 5");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S3Problem6 {
public static void main(String[] args) {
System.out.println("Problem 6");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S3Problem7 {
public static void main(String[] args) {
System.out.println("Problem 7");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S3Problem8 {
public static void main(String[] args) {
System.out.println("Problem 8");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class Session7 {
public static void main(String[] main) {
System.out.println("Session 7");
// Example 1
// Example 2
// Example 3
// Example 4
// Example 5
// Example 6
// Example 7
// Example 8
// Example 9
// Example 10
// Example 11
// Example 12
// Example 13
// Example 14
// Example 15
// example1 method call
// example2 method call
}
// example1 method definition
// example2 method definition
}import java.util.*;
public class S7Problem1 {
public static void main(String[] args) {
System.out.println("Problem 1");
}
}import java.util.*;
public class S7Problem2 {
public static void main(String[] args) {
System.out.println("Problem 2");
}
}import java.util.*;
public class S7Problem3 {
public static void main(String[] args) {
System.out.println("Problem 3");
}
}import java.util.*;
public class EmailDomain
{
public static String getDomain(String email)
{
// TODO: Use indexOf and substring only.
// Example: "[email protected]" → "school.edu"
String domain;
return domain;
}
public static void main(String[] args)
{
// Do not change main!
Scanner in = new Scanner(System.in);
System.out.print("What is your email address? ");
String email = in.nextLine();
System.out.println("Domain: " + getDomain(email));
in.close();
}
}import java.util.*;
public class FileExtension
{
public static String getExtension(String fileName)
{
// TODO: Use indexOf and substring only.
// Example: "photo.jpeg" → "jpeg"
String ext;
return ext;
}
public static void main(String[] args)
{
// Do not change main!
Scanner in = new Scanner(System.in);
System.out.print("What is the filename? ");
String fileName = in.nextLine();
System.out.println("Extension: " + getExtension(fileName));
in.close();
}
}
import java.util.*;
public class FirstSentence
{
public static String getFirstSentence(String paragraph)
{
// TODO: Use indexOf and substring only.
// Assume sentences end with a period '.'
// Return everything up to and including the first '.'
// Example:
// "Today is Monday. We have class." → "Today is Monday."
String first;
return first;
}
public static void main(String[] args)
{
// Do not change main!
Scanner in = new Scanner(System.in);
System.out.print("What is the paragraph? ");
String paragraph = in.nextLine();
System.out.println("First sentence: " + getFirstSentence(paragraph));
in.close();
}
}
import java.util.*;
public class AreaCode
{
public static String getAreaCode(String phone)
{
// TODO: Use indexOf and substring only.
// Assume the phone number format is "(###) ###-####"
// Example: "(212) 000-0000" → "212"
String code;
return code;
}
public static void main(String[] args)
{
// Do not change main!
Scanner in = new Scanner(System.in);
System.out.print("What is the phone number (000) 000-0000 ? ");
String phone = in.nextLine();
System.out.println("Area code: " + getAreaCode(phone));
in.close();
}
}
import java.util.*;
public class SecretPhrase
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// The secret phrase
String secret = null;
// --- Step 1: Give the user hints ---
// --- Step 2: Let the user ask questions ---
// --- Step 3: Let the user guess the phrase ---
// --- Step 4: Compare using equals()
in.close();
}
}
public class TypesDemo {
public static void main(String[] args) {
System.out.println("Types Demo");
// 1. byte: 8-bit signed integer
// 2. short: 16-bit signed integer
// 3. int: 32-bit signed integer
// 4. long: 64-bit signed integer (needs 'L' at the end for large values)
// 5. float: 32-bit floating point (needs 'f' at the end)
// 6. double: 64-bit floating point
// 7. char: single 16-bit Unicode character
// 8. boolean: true or false
// Print them
// String
}
}public class ArithmeticDemo {
public static void main(String[] args) {
System.out.println("Arithmetic Demo");
// Integer arithmetic
int a = 15;
int b = 4;
// Double arithmetic
double x = 15.0;
double y = 4.0;
}
}
// import all the classes and interfaces from the java.util package into your program.
import java.util.*;
public class ScannerExample {
public static void main(String[] args) {
System.out.println("Scanner Example Code");
// 1. Print a message to the user
// 2. Initialize the Scanner. Declare a variable named in
// that reads from System.in
// 3. Create a variable and assign it to the value returned by nextLine
// The Scanner class provides a method called nextLine that reads a
// line of input from the keyboard and returns a String.
// 4. Print the value of the variable
// 5. Close the Scanner
}
}import java.util.*;
public class ScannerExample2 {
public static void main(String[] args) {
System.out.println("Scanner Example 2 Code");
Scanner in = new Scanner(System.in);
System.out.print("What's your age? ");
int age = in.nextInt();
// add code to fix the "Scanner bug"
System.out.print("What's your name? ");
String line = in.nextLine();
System.out.println("Name: " + line);
System.out.println("Age: " + age);
in.close();
}
}import java.util.*;
public class CastingDemo {
public static void main(String[] args) {
System.out.println("Casting Demo");
// Example 1
// Example 2
// Example 3
// Example 4
// Example 5
// Example 6
// Example 7
// Example 8
}
}public class S2Problem1 {
public static void main(String[] args) {
System.out.println("Problem 1");
}
}public class S2Problem2 {
public static void main(String[] args) {
System.out.println("Problem 2");
}
}public class S2Problem3 {
public static void main(String[] args) {
System.out.println("Problem 3");
}
}public class S2Problem4 {
public static void main(String[] args) {
System.out.println("Problem 4");
}
}public class S2Problem5 {
public static void main(String[] args) {
System.out.println("Problem 5");
}
}public class S2Problem6 {
public static void main(String[] args) {
System.out.println("Problem 6");
}
}public class S2Problem10 {
public static void main(String[] args) {
System.out.println("Problem 10");
}
}public class S2Problem11 {
public static void main(String[] args) {
System.out.println("Problem 11");
}
}public class S2Problem12 {
public static void main(String[] args) {
System.out.println("Problem 12");
}
}import java.util.*;
public class TipCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the total bill amount: ");
System.out.print("Enter the tip: ");
System.out.println("Bill Amount: $");
System.out.println("Tip (specify the %): $");
System.out.println("Total Amount: $");
}
}
import java.util.*;
public class CurrencyConverter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter amount in USD: ");
System.out.println("Amount in Euro EUR: ");
System.out.println("Amount in British Pound GBP: ");
System.out.println("Amount in Japanese Yen JPY: ");
System.out.println("Amount in Indian Rupee INR: ");
System.out.println("Amount in Australian Dollar AUD: ");
System.out.println("Amount in Canadian Dollar CAD: ");
System.out.println("Amount in Swiss Franc CHF: ");
System.out.println("Amount in Chinese Yuan Renminbi CNY: ");
System.out.println("Amount in Malasian Ringgit MYR: ");
System.out.println("Amount in Singapore Dollar SGD: ");
}
}
import java.util.*;
public class CompoundInterestCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the principal amount: ");
System.out.print("Enter the annual interest rate (in decimal): ");
System.out.print("Enter the number of years: ");
System.out.println("The amount after " + " years is: ");
}
}import java.util.*;
public class Session9v1 {
public static void main(String[] args) {
System.out.println("Session 9");
// Example 1 method call
// Example 2 method call
// Example 3 method call
}
// example1 method definition
public static void example1() {
Scanner in = new Scanner(System.in);
// add code
}
// example2 method definition
public static void example2() {
Scanner in = new Scanner(System.in);
// add code
}
// example3 method definition
public static void example3() {
Scanner in = new Scanner(System.in);
System.out.print("Number of Credits: ");
int creditsCompleted = in.nextInt();
in.nextLine();
System.out.print("GPA: ");
double gpa = in.nextDouble();
in.nextLine();
System.out.print("Completed Capstone [true/false]: ");
boolean hasPassedCapstone = in.nextBoolean();
// add code
}
}
import java.util.*;
public class S9Problem1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 1");
}
}When multiple classes contain common attributes and behaviors, programmers create a new class containing the shared attributes and behaviors forming a hierarchy. Modifications made at the highest level of the hierarchy apply to the subclasses.
Call methods in an inheritance relationship.
Utilize the Object class through inheritance.
At compile time, methods in or inherited by the declared type determine the correctness of a non-static method call.
At run-time, the method in the actual object type is executed for a non-static method call.
import java.util.*;
public class S9Problem2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 2");
}
}import java.util.*;
public class S9Problem3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 3");
}
}import java.util.*;
public class Session9v2 {
public static void main(String[] args) {
System.out.println("Session 9");
// Menu
// setup Scanner
// switch statement
}
// example2 method definition
// example3 method definition
// example4 method definition
// example5 method definition
// example6 method definition
// example7 method definition
// example8 method definition
// example9 method definition
// example10 method definition
// example11 method definition
// example12 method definition
}import java.util.*;
public class S9Problem4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 4");
System.out.print("Enter a number (1–7): ");
int day = in.nextInt();
in.nextLine();
if (day == 1)
System.out.println("Sunday");
else if (day == 2)
System.out.println("Monday");
else if (day == 3)
System.out.println("Tuesday");
else if (day == 4)
System.out.println("Wednesday");
else if (day == 5)
System.out.println("Thursday");
else if (day == 6)
System.out.println("Friday");
else if (day == 7)
System.out.println("Saturday");
else
System.out.println("Invalid number!");
}
}import java.util.*;
public class S9Problem5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 5");
System.out.print("Enter first number: ");
double num1 = in.nextDouble();
in.nextLine();
System.out.print("Enter operator (+, -, *, /): ");
char op = in.next().charAt(0);
System.out.print("Enter second number: ");
double num2 = in.nextDouble();
in.nextLine();
if (op == '+')
System.out.println(num1 + num2);
else if (op == '-')
System.out.println(num1 - num2);
else if (op == '*')
System.out.println(num1 * num2);
else if (op == '/')
System.out.println(num1 / num2);
else
System.out.println("Invalid operator!");
}
}import java.util.*;
public class S9Problem6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 6");
}
}import java.util.*;
public class S9Problem7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 7");
}
}import java.util.*;
public class S9Problem8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 8");
}
}import java.util.*;
public class S9Problem9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 9");
}
}import java.util.*;
public class S9Problem10 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 10");
}
}import java.util.*;
public class S9Problem11 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 11");
}
}import java.util.*;
public class S9Problem12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 12");
}
}import java.util.*;
public class S9Problem13 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 13");
}
}import java.util.*;
public class S9Problem14 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 13");
}
}import java.util.*;
public class S9Problem15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 15");
}
}import java.util.*;
public class S9Problem16 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 16");
}
}import java.util.*;
public class Week20 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 20" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
System.out.println("Q - Quit");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
case "Q":
System.out.println("Quitting..!");
break;
}
}
// example1 method
public static void example1() {
// Create Objects
// Create an array of Felines
// populate the array with Cat and Tiger objects
// loop through array and call method
// instanceOf Examples
// is catty a Feline?
// is tigris a Feline?
// is felix a Cat?
}
// example2 method
public static void example2() {
// create a new Zoo
// Adding different animals to the zoo
// Displaying all animals in the zoo
}
// example3 method
public static void example3() {
// Create Object
}
// example4 method
public static void example4() {
// Create Object
}
}
// class header
public class Feline {
// private instance variable
// constructor
// constructor
// methods
}// class header
public class Tiger extends Feline {
// methods
}// class header
public class Cat extends Feline {
// constructors
// methods
}import java.util.*;
// Base class representing a generic Animal (IS-A relationship)
class Animal {
// Method to make a generic animal sound
public void makeSound() {
System.out.println("Animals make sounds");
}
}
// Subclass representing a Bear (IS-A Animal)
class Bear extends Animal {
// Method specific to Bear
public void growl() {
System.out.println("Bears like to growl");
}
}
// Subclass representing a Lion (IS-A Animal)
class Lion extends Animal {
// Method specific to Lion
public void roar() {
System.out.println("Lions like to roar");
}
}
// Subclass representing an Elephant (IS-A Animal)
class Elephant extends Animal {
// Method specific to Elephant
public void forage() {
System.out.println("Elephants like to forage");
}
}
// Zoo class HAS-A relationship with a list of animals
class Zoo {
// ArrayList to store Animal objects
// Constructor to initialize the list of animals
// Add an animal to the zoo
// Method to display the sounds of all animals in the zoo
// Check if the animal is a Bear
// Check if the animal is a Lion
// Check if the animal is an Elephant
}import java.util.*;
// Superclass
// Subclass:
// Subclass:
// Subclass:
// Subclass:
// Main class
public class Professions {
public static void main(String[] args) {
// create an ArrayList of Professions
// Creating instances of each profession
// Adding objects to the ArrayList
// Loop through ArrayList of Professions using instanceof and calling methods
}
}class CharacterBase {
void action() {
System.out.println("Ready to fight! ");
}
}
class Warrior extends CharacterBase {
public Warrior() {
System.out.println("Equipped with sword! ");
super.action();
}
}
class Knight extends Warrior {
public Knight() {
System.out.println("For the kingdom!");
}
}
public class MainCharacter {
public static void main(String[] args) {
Knight k = new Knight();
}
}// A class called Rectangle that has two instance variables, length and width,
// a constructor that initializes them, and a method called draw that uses nested loops
// to draw a length x width rectangle of stars.
class Rectangle {
private int length;
private int width;
// Constructor that initializes length and width
public Rectangle(int l, int w) {
length = l;
width = w;
}
// Method to draw a rectangle of stars based on length and width
public void draw() {
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++) {
System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
// Add an area method to compute the area of the rectangle
}
// Make the class Square below inherit from Rectangle
// Add a Square constructor with 1 argument for a side
// that calls Rectangle's constructor with 2 arguments using super
// Add another subclass called LongRectangle which inherits from Rectangle
// but has the additional condition that the length is always 2 x the width
public class SquareDemo {
public static void main(String[] args) {
// Create a Rectangle object and draw it
Rectangle r = new Rectangle(3, 5);
// System.out.println("Area of rectangle: " + r.area());
r.draw();
// Uncomment the objects to test the squares
// Square s1 = new Square(1);
// System.out.println("Area of square with side 1: " + s1.area());
// s1.draw();
// Square s2 = new Square(3);
// System.out.println("Area of square with side 3: " + s2.area());
// s2.draw();
// System.out.println();
// Uncomment the objects to test the rectangle
// LongRectangle lr = new LongRectangle(4);
// System.out.println("Area of long rectangle with length 4: " + lr.area());
// lr.draw();
}
}import java.util.*;
public class Session12 {
public static void main(String[] args) {
System.out.println("Session 12");
Scanner in = new Scanner(System.in);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
// setup Scanner
System.out.print("Choice: ");
String choice = in.nextLine();
// switch statement
switch (choice) {
case "E1":
break;
case "E2":
break;
case "E3":
break;
case "E4":
break;
case "E5":
break;
case "E6":
break;
case "E7":
break;
case "E8":
break;
case "E9":
break;
case "E10":
break;
case "E11":
break;
case "E12":
break;
case "E13":
break;
case "E14":
break;
default:
System.out.println("Invalid choice");
break;
}
}
// example1 method definition
// example2 method definition
// example3 method definition
// example4 method definition
// example5 method definition
// example6 method definition
// example7 method definition
// example8 method definition
// example9 method definition
// example10 method definition
// example11 method definition
// example12 method definition
// example13 method definition
// example14 method definition
}
import java.util.*;
public class S12Problem1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 1");
}
public static int countFactors(int n) {
return 0; // placeholder
}
}import java.util.*;
public class S12Problem2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 2");
}
public static int gcd(int a, int b) {
int gcd = 1;
return 0; // placeholder
}
}import java.util.*;
public class S12Problem3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 3");
}
public static boolean isFibonacci(int n) {
return false; // placeholder
}
}import java.util.*;
public class S12Problem4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 4");
}
public static void printDigitSum(int n) {
}
}import java.util.*;
public class S12Problem5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 5");
}
public static int getKthDigit(int n, int k) {
return -1; // placeholder
}
}import java.util.*;
public class S12Problem6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 6");
}
public static void printDigitsReverse(int n) {
}
}import java.util.*;
public class S12Problem7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 7");
}
}import java.util.*;
public class S12Problem8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 8");
}
}import java.util.*;
public class S17Problem3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 9");
}
}import java.util.*;
public class S12Problem10 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 10");
}
}import java.util.*;
public class S12Problem11 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 11");
}
}import java.util.*;
public class S12Problem12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 12");
}
}import java.util.*;
public class S12Problem13 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 13");
}
}import java.util.*;
public class Session6 {
public static void main(String[] args) {
System.out.println("Session 6");
// example1 method call
// example2 method call
}
// example1 method definition
public static void example1() {
// Create Counter object
// Increment counter
// Print counter variable
// Reset counter value
// Print counter value (again)
// click twice and print the value
//
}
// example2 method definition
public static void example2() {
}
}public class Ant {
// instance variable
// Constructor
// display method
// main method
public static void main(String[] args) {
System.out.println("Ant Class Demo");
// Example 1
// Example 2
// Example 3
}
}import java.util.*;
public class Week15 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 15" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
System.out.println("Q - Quit");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
case "E5":
System.out.println("Example 5");
example5();
break;
case "E6":
System.out.println("Example 6");
example6();
break;
case "E7":
System.out.println("Example 7");
example7();
break;
case "E8":
System.out.println("Example 8");
example8();
break;
case "E9":
System.out.println("Example 8");
example9();
break;
case "Q":
System.out.println("Quitting..!");
break;
}
}
// example1 method
public static void example1() {
// declares an array of integers
// create an empty array of size 3
// print the values in the scores array
// declare and create an array of doubles
// assign values to each index position
// print the values in the prices array
}
// example2 method
public static void example2() {
// declare an array of String elements
// assign values to each index position
// print the values in the friends array
}
// example3 method
public static void example3() {
// create an array with an initializer list
// .length property
}
// example4 method
public static void example4() {
// declare and create an array
int[] arr = { 10, 20, 30, 40, 50 };
// for loop to traverse the array
}
// example5 method
public static void example5() {
// declare and create an array
double[] arr = { 1.1, 2.2, 3.3, 4.4, 5.5 };
// while loop to traverse the array
}
// example6 method
public static void example6() {
// declare and create an array
int[] arr = { 1, 2, 3, 4, 5 };
// accumulator pattern
}
// example7 method
public static void example7() {
// declare array
int[] arr = { 50, 100, 75, 25, 80 };
// initialize max to first value
// for loop
}
// example8 method
public static void example8() {
// declare array numbers
int[] numbers = { 1, 2, 3, 4, 5 };
// pass numbers to printArray method
// pass numbers to changeArray method
}
// example9 method
public static void example9() {
// declare array
int[] numArray = {3, 8, -3, 2, 1};
// create an instance of ArrayWorker
// call mystery method
}
// changeArray method
public static void changeArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
}
// printArray method
public static void printArray(int[] arr) {
System.out.println("Print Array");
System.out.println("Index\tValue");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + "\t" + arr[i]);
}
}
}
import java.util.*;
public class W15Problem1
{
public static void main(String[] args)
{
System.out.println("Problem 1");
}
}public class Flower {
// instance variable
// Constructor
// method
// main method
}// class header
// private instance variable(s)
// Constructor
// accessor method(s)
// mutator method(s)
/**
* The Point class represents a point in 2D space with x and y coordinates.
* It provides methods to move the point and calculate distance.
*/
public class Point {
// Instance variables
/**
* No argument constructor
*/
/**
* Parameterized constructor that sets x and y
* @param x the x-coordinate
* @param y the y-coordinate
*/
// Getters and setters
/**
* Moves the point to new coordinates.
* @param newX new x-coordinate
* @param newY new y-coordinate
*/
/**
* Shifts the point by a given amount in x and y directions.
* @param dx change in x
* @param dy change in y
*/
/**
* Displays the coordinates of the point.
*/
}public class StringDemo {
public static void main(String[] args) {
System.out.println("String Demo");
}
}import java.util.*;
public class S6Problem1 {
public static void main(String[] args) {
System.out.println("Problem 1");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem2 {
public static void main(String[] args) {
System.out.println("Problem 2");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem3 {
public static void main(String[] args) {
System.out.println("Problem 3");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem4 {
public static void main(String[] args) {
System.out.println("Problem 4");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem5 {
public static void main(String[] args) {
System.out.println("Problem 5");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem6 {
public static void main(String[] args) {
System.out.println("Problem 6");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem7 {
public static void main(String[] args) {
System.out.println("Problem 7");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem8 {
public static void main(String[] args) {
System.out.println("Problem 8");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem9 {
public static void main(String[] args) {
System.out.println("Problem 9");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S6Problem10 {
public static void main(String[] args) {
System.out.println("Problem 10");
Scanner in = new Scanner(System.in);
}
}/**
* The Pet class represents a pet with a name, species, and age.
* Each Pet object stores information about ONE specific pet.
*/
public class PetTracker {
// instance variables (aka fields / attributes)
private String name;
private String species;
private int age; // in years
/**
* Constructor: creates a new Pet with a given name, species, and age.
*
* @param petName the pet's name
* @param petSpecies the type of animal (e.g. "dog", "cat", "lizard")
* @param petAge the pet's age in years
*/
public Pet(String petName, String petSpecies, int petAge) {
name = petName;
species = petSpecies;
age = petAge;
}
/**
* Returns the pet's name.
*/
public String getName() {
return name;
}
/**
* Returns the pet's species.
*/
public String getSpecies() {
return species;
}
/**
* Returns the pet's age.
*/
public int getAge() {
return age;
}
/**
* Increases the pet's age by 1 year.
* This simulates having a birthday.
*/
public void haveBirthday() {
age = age + 1;
System.out.println(name + " just had a birthday! Age is now " + age);
}
/**
* Prints a short summary of the pet.
* Example: "Pumpkin is a 3-year-old cat."
*/
public void printInfo() {
System.out.println(name + " is a " + age + "-year-old " + species + ".");
}
/**
* This class will be used to TEST the Pet class.
* You will add code in main() in Parts A–D.
*/
public static void main(String[] args) {
// You will write your code here for the lab
}
}import java.util.*;
public class W15Problem2
{
public static void main(String[] args)
{
System.out.println("Problem 2");
}
}import java.util.*;
public class W15Problem3
{
public static void main(String[] args)
{
System.out.println("Problem 3");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W15Problem4
{
public static void main(String[] args)
{
System.out.println("Problem 4");
}
}import java.util.*;
public class W15Problem5
{
public static void main(String[] args)
{
System.out.println("Problem 5");
}
}import java.util.*;
public class W15Problem6
{
public static void main(String[] args)
{
System.out.println("Problem 6");
}
}public class ArrayWorker {
// private instance variable
private int[] values;
// constructor
public ArrayWorker(int[] values) {
this.values = values;
}
public void mystery() {
for (int i = values.length / 2; i < values.length; i++) {
values[i] = values[i] * 2;
}
}
}import java.util.*;
public class W15Problem7
{
public static void main(String[] args)
{
System.out.println("Problem 7");
}
}import java.util.*;
public class W15Problem8
{
public static void main(String[] args)
{
System.out.println("Problem 8");
}
}public class W15Problem9
{
public static void main(String[] args)
{
int[] scores = {10, 9, 8, 7};
// Make this loop print out all the scores!
for (int i = 1; i <= scores.length; i++)
{
System.out.println(scores[i]);
}
}
}public class W15Problem10
{
private String[] arr = {"Hello", "Hey", "Good morning!"};
public int findString(String target)
{
String word = null;
for (int index = 0; index < arr.length; index++)
{
word = arr[index];
if (word.equals(target))
{
return index;
}
else
{
return -1;
}
}
return -1;
}
public static void main(String[] args)
{
W15Problem10 sWorker = new W15Problem10();
System.out.println(sWorker.findString("Hey"));
}
}
/**
* A TicketMachine that sells tickets for a fixed price.
* Demonstrates Javadoc comments with preconditions and postconditions.
*
* @author An AP Java student
* @version 1.0
* @since 2025
*/
public class TicketMachine {
private int price; // price of a single ticket
private int balance; // money inserted by the user
private int total; // total money collected by the machine
/**
* Constructs a TicketMachine with the given ticket price.
*
* @param ticketPrice the price of a single ticket
* Precondition: ticketPrice > 0
* Postcondition: price is set to ticketPrice, balance and total are 0
*/
public TicketMachine(int ticketPrice) {
price = ticketPrice;
balance = 0;
total = 0;
}
/**
* Inserts money into the machine.
*
* @param amount the amount of money to insert
* Precondition: amount > 0
* Postcondition: balance is increased by amount
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance += amount;
}
}
/**
* Prints a ticket if enough money has been inserted.
*
* Precondition: balance >= price
* Postcondition: balance is decreased by price,
* total is increased by price
*/
public void printTicket() {
if (balance >= price) {
// simulate ticket printing
System.out.println("##################");
System.out.println("# Ticket");
System.out.println("# Price: " + price + " cents");
System.out.println("##################");
System.out.println();
balance -= price;
total += price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Returns the current balance (unspent money).
*
* @return the current balance
* Precondition: none
* Postcondition: balance remains unchanged
*/
public int getBalance() {
return balance;
}
/**
* Empties the machine of all collected money.
*
* @return the total money collected
* Precondition: none
* Postcondition: total is reset to 0
*/
public int emptyMachine() {
int amount = total;
total = 0;
return amount;
}
}
public class GamePoints {
public static void main(String[] args) {
int level1Points = 120;
int level2Points = 45;
int totalPoints = level1Points + level2Points;
int pointDifference = level1Points - level2Points;
int bonusMultiplier = level1Points * 2;
int averagePoints = totalPoints / 2;
int remainderPoints = totalPoints % 2;
System.out.println(totalPoints);
System.out.println(pointDifference);
System.out.println(bonusMultiplier);
System.out.println(averagePoints);
System.out.println(remainderPoints);
}
}public class OldMacDonaldv1 {
public static void main(String args[]) {
System.out.println("Old MacDonald had a farm.");
System.out.println("E-I-E-I-O");
System.out.println("And on this farm, they had a cow.");
System.out.println("E-I-E-I-O");
System.out.println("With a moo moo here and a moo moo there");
System.out.println("Here a moo, there a moo, everywhere a moo moo");
System.out.println("Old MacDonald had a farm");
System.out.println("E-I-E-I-O");
}
}public class OldMacDonaldv2 {
public static void intro() {
System.out.println("Old MacDonald had a farm");
chorus();
}
public static void chorus() {
System.out.println("E-I-E-I-O");
}
public static void main(String[] args) {
intro();
System.out.println("And on that farm they had a cow.");
chorus();
System.out.println("With a moo moo here and a moo moo there");
System.out.println("Here a moo, there a moo, everywhere a moo moo");
// TODO:
// 1. Call the method intro()
// 2. Print out the line "And on that farm..."
// with a duck or another animal
// 3. Call the method chorus
// 4. Print out the lines with the appropriate animal sounds
// 5. Call the method intro again
}
}public class OldMacDonaldv3 {
public static void main(String args[]) {
System.out.println("Old MacDonald had a farm.");
System.out.println("E-I-E-I-O");
System.out.println("And on this farm, they had a cow.");
System.out.println("E-I-E-I-O");
System.out.println("With a moo moo here and a moo moo there");
System.out.println("Here a moo, there a moo, everywhere a moo moo");
System.out.println("Old MacDonald had a farm");
System.out.println("E-I-E-I-O");
System.out.println("And on this farm, they had a duck.");
System.out.println("E-I-E-I-O");
System.out.println("With a quack quack here and a quack quack there");
System.out.println("Here a quack, there a quack, everywhere a quack quack");
System.out.println("Old MacDonald had a farm");
System.out.println("E-I-E-I-O");
}
}public class OldMacDonaldv4 {
public static void main(String args[]) {
intro();
verse("cow", "moo");
intro();
verse("duck", "quack");
intro();
}
/**
* The verse method prints out a verse for any given animal and sound.
*
* @param animal the name of the animal
* @param sound the sound the animal makes
*/
public static void verse(String animal, String sound) {
System.out.println("And on this farm, they had a " + animal);
chorus();
System.out.println("With a " + sound + " " + sound
+ " here and a " + sound + " " + sound + " there");
System.out.println("Here a " + sound
+ ", there a " + sound
+ ", everywhere a " + sound + " " + sound);
}
/**
* The intro method prints the introductory line of the song
* and then calls the chorus method.
*/
public static void intro() {
System.out.println("Old MacDonald had a farm");
chorus();
}
/**
* The chorus method prints the repeating "E-I-E-I-O" line.
*/
public static void chorus() {
System.out.println("E-I-E-I-O");
}
}public class AntsSong
{
public static void chorus(String num)
{
System.out.println("The ants go marching " + num
+ " by " + num + " hurrah, hurrah");
System.out.println("The ants go marching " + num
+ " by " + num + " hurrah, hurrah");
}
public static void verse(String num, String action)
{
System.out.println("The ants go marching " + num + " by " + num);
System.out.println("The little one stops to " + action);
System.out.println("And they all go marching down to the ground");
System.out.println("To get out of the rain, BOOM! BOOM! BOOM! BOOM!\n");
}
public static void main(String args[])
{
// Call the chorus and verse methods
// with the correct arguments
// to print out all three verses above.
}
}/**
* The Poem class...
*
* @author
* @since
* @version
*/
import java.util.*;
public class PoemLab {
// prints a simple header
public static void intro() {
System.out.println("Stopping by Woods — A Programmed Poem");
System.out.println("in the style of Robert Frost (1923)");
System.out.println("--------------------------------------");
System.out.println();
}
/**
* Prints a 4-line stanza inspired by the poem's scene/thought pattern.
* @param place a location detail (e.g., "the woods near the village")
* @param time a time/mood detail (e.g., "this quiet winter evening")
* @param image a sensory image (e.g., "the sweep of easy wind and downy flake")
* @param innerThought a reflective line (e.g., "I watch the dark fill up the snow")
*/
public static void stanza(String place, String time, String image, String innerThought) {
System.out.println("Whose " + place + " these are, I think I know;");
System.out.println("It is " + time + " and softly still.");
System.out.println("I notice " + image + ", slow and low,");
System.out.println(innerThought + ".");
System.out.println();
}
// Refrain method: echo the poem’s famous closing repetition.
public static void chorus() {
System.out.println("And miles to go before I sleep,");
System.out.println("And miles to go before I sleep.");
System.out.println();
}
public static void main(String[] args) {
// Initialize the Scanner. Declare a variable named in
// that reads from System.in
Scanner in = new Scanner(System.in);
intro();
// Example stanza calls (you must add/modify your own):
stanza(
"woods by the village road",
"this hush of falling snow tonight",
"the whispering wind and downy flakes",
"I pause and let the quiet fill"
);
stanza(
"quiet grove beyond the lake",
"a late and silver-stitched twilight",
"hoof-bells chiming once, then still",
"I weigh the pull of rest against the path"
);
// TODO #1:
// Write a THIRD stanza with your own vivid imagery.
// Change all four parameters so the scene evolves.
// stanza("<place>", "<time>", "<image>", "<innerThought>");
// TODO #2
// Write a FOURTH stanza that adds a subtle shift in mood or choice.
// stanza("<place>", "<time>", "<image>", "<innerThought>");
// TODO #3:
// After your FINAL stanza, call the chorus to close the poem:
// chorus();
}
}import java.util.*;
public class Week17 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 17" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
System.out.println("Q - Quit");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
case "E5":
System.out.println("Example 5");
example5();
break;
case "E6":
System.out.println("Example 6");
example6();
break;
case "Q":
System.out.println("Quitting..!");
break;
}
}
// example1 method
public static void example1() {
// declare and initalize an ArrayList of students
// add elements
// print elements
// insert "Abi" at index 0
// set "Devin" at index 3
// print elements
}
// example2 method
public static void example2() {
// declare and initalize an ArrayList of numbers
// add elements
// get elements
}
// example3 method
public static void example3() {
// Create an ArrayList of top colleges
ArrayList<String> colleges = new ArrayList<>();
// Add top 10 colleges to the list
colleges.add("Massachusetts Institute of Technology (MIT)");
colleges.add("Stanford University");
colleges.add("Harvard University");
colleges.add("California Institute of Technology (Caltech)");
colleges.add("University of Chicago");
colleges.add("Princeton University");
colleges.add("Yale University");
colleges.add("Columbia University");
colleges.add("University of Pennsylvania");
colleges.add("Duke University");
// for loop to traverse the ArrayList
}
// example4 method
public static void example4() {
// Create an ArrayList of words
ArrayList<String> words = new ArrayList<>(Arrays.asList("Java", "is", "awesome"));
// replace the element at index 1 (second element)
}
// example4 method
public static void example5() {
// Create an ArrayList of top global universities
ArrayList<String> universities = new ArrayList<>();
// Add top 10 universities globally
universities.add("Massachusetts Institute of Technology (MIT) - USA");
universities.add("Stanford University - USA");
universities.add("Harvard University - USA");
universities.add("University of Cambridge - UK");
universities.add("University of Oxford - UK");
universities.add("California Institute of Technology (Caltech) - USA");
universities.add("Imperial College London - UK");
universities.add("ETH Zurich - Switzerland");
universities.add("University College London (UCL) - UK");
universities.add("University of Chicago - USA");
// Remove by index
// Remove by value
// Print the list of top global universities
}
// example6 method
public static void example6() {
// Create an ArrayList of numbers
ArrayList<Integer> numArray = new ArrayList<>();
numArray.add(10);
numArray.add(-5);
numArray.add(20);
numArray.add(-15);
numArray.add(30);
// while loop
// while loop and deleting
// enhanced for loop
}
}
import java.util.*;
public class W17Problem1
{
public static void main(String[] args)
{
System.out.println("Problem 1");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W17Problem2
{
public static void main(String[] args)
{
System.out.println("Problem 2");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class ReverseDigits
{
/** A list of digits */
private ArrayList<Integer> digitList;
/** Constructs a list of digits from the given number */
public ReverseDigits(int number)
{
// initialize digitList to an empty ArrayList of Integers
digitList = new ArrayList<>();
// Special case for number 0
// Use a while loop to add each digit in number to digitList
// Extract the last digit
// Remove the last digit
// Reverse the digits to maintain original order
Collections.reverse(digitList);
}
/** Returns the string representation of the digits list */
public String toString()
{
return digitList.toString();
}
public static void main(String[] args)
{
ReverseDigits d1 = new ReverseDigits(154);
System.out.println(d1); // Output: [1, 5, 4]
}
}import java.util.*;
public class W17Problem3
{
public static void main(String[] args)
{
System.out.println("Problem 3");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W17Problem4
{
public static void main(String[] args)
{
System.out.println("Problem 4");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W17Problem5
{
public static void main(String[] args)
{
System.out.println("Problem 5");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W17Problem6
{
public static void main(String[] args)
{
System.out.println("Problem 6");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W17Problem7
{
public static void main(String[] args)
{
System.out.println("Problem 7");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W17Problem8
{
public static void main(String[] args)
{
System.out.println("Problem 8");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W17Problem9
{
public static void main(String[] args)
{
System.out.println("Problem 9");
// Rewrite this code to use an ArrayList instead of an array
String[] toDoList = new String[3];
toDoList[0] = "Do homework";
toDoList[1] = "Help make dinner";
toDoList[2] = "Call grandma";
// changing element 1
toDoList[1] = "Order pizza";
System.out.println(toDoList.length + " things to do!");
System.out.println("Here's the first thing to do: " + toDoList[0]);
// remove item 0 and move everything down
// (this can be done in one method call with ArrayList)
toDoList[0] = toDoList[1];
toDoList[1] = toDoList[2];
toDoList[2] = "";
System.out.println("Here's the next thing to do: " + toDoList[0]);
}
}import java.util.*;
public class Session11 {
public static void main(String[] args) {
System.out.println("Session 11");
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E0":
System.out.println("Example 0");
example0();
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
case "E5":
System.out.println("Example 5");
example5();
break;
case "E6":
System.out.println("Example 6");
example6();
break;
case "E7":
System.out.println("Example 7");
example7();
break;
case "E8":
System.out.println("Example 8");
example8();
break;
case "E9":
System.out.println("Example 9");
example9();
break;
case "E10":
System.out.println("Example 10");
example10();
break;
case "E11":
System.out.println("Example 11");
example11();
break;
case "E12":
System.out.println("Example 12");
example12();
break;
case "E13":
System.out.println("Example 13");
example13();
break;
case "E14":
System.out.println("Example 14");
example14();
break;
case "E15":
System.out.println("Example 15");
example15();
break;
case "E16":
System.out.println("Example 16");
example16();
break;
case "E17":
System.out.println("Example 17");
example17();
break;
case "E18":
System.out.println("Example 18");
example18();
break;
}
}
// example0 method
public static void example0() {
}
// example1 method
public static void example1() {
}
// example2 method
public static void example2() {
}
// example3 method
public static void example3() {
}
// example4 method
public static void example4() {
}
// example5 method
public static void example5() {
}
// example6 method
public static void example6() {
}
// example7 method
public static void example7() {
}
// example8 method
public static void example8() {
}
// example9 method
public static void example9() {
}
// example10 method
public static void example10() {
}
// example11 method
public static void example11() {
}
// example12 method
public static void example12() {
}
// example13 method
public static void example13() {
}
// example14 method
public static void example14() {
}
// example15 method
public static void example15() {
}
// example16 method
public static void example16() {
}
// example17 method
public static void example17() {
}
// example18 method
public static void example18() {
}
}import java.util.*;
public class S11Problem1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 1");
}
}import java.util.*;
public class Week14 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 14" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
}
}
// example1 method
public static void example1() {
// create CollegeStudent object
// call methods
}
// example2 method
public static void example2() {
// create CollegeStudent object
}
// example3 method
public static void example3() {
// create CollegeStudent object
}
// example4 method
public static void example4() {
// create two high school students
// call printStudentCounter method
}
}/**
* Class CollegeStudent keeps track of the name, email, and ID of a college student.
*/
public class CollegeStudent
{
// private instance variables
/**
* Constructor for CollegeStudent.
* @param name the initial name of the student
* @param email the initial email of the student
* @param ID the initial ID of the student
*/
/**
* Gets the name of the student.
* @return the name of the student
*/
/**
* Gets the email of the student.
* @return the email of the student
*/
/**
* Gets the ID of the student.
* @return the ID of the student
*/
/**
* Returns a string representation of the CollegeStudent object.
* @return a string representation of the CollegeStudent object
*/
// Accessor methods (getters)
/**
* Sets the name of the college student.
* @param name the new name of the student
*/
/**
* Sets the email of the college student.
* @param email the new email of the student
*/
/**
* Sets the ID of the college student.
* @param id the new ID of the student
*/
}
import java.util.*;
public class Week21 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 21" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
System.out.println("Q - Quit");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "Q":
System.out.println("Quitting..!");
break;
}
}
// example1 method
public static void example1() {
// Create a Greeter
// Create a MeanGreeter
}
// example2 method
public static void example2() {
// Create a Greeter
// Create a MeanGreeter
}
// example3 method
public static void example3() {
}
}
public class Greeter {
// greet method no parameters
// greet method with one parameter
}import java.util.*;
public class S11Problem2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 2");
}
}import java.util.*;
public class S11Problem3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 3");
}
}import java.util.*;
public class S11Problem4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 4");
}
}import java.util.*;
public class S11Problem5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 5");
}
}import java.util.*;
public class S11Problem6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 6");
}
}import java.util.*;
public class S11Problem7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 7");
}
}import java.util.*;
public class S11Problem8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 8");
}
}import java.util.*;
public class S11Problem9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 9");
}
}import java.util.*;
public class S11Problem10 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 10");
}
}import java.util.*;
public class S11Problem11 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 11");
}
}import java.util.*;
public class S11Problem12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 12");
}
}import java.util.*;
public class S11Problem13 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 13");
}
}import java.util.*;
public class S11Problem14 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 14");
}
}import java.util.*;
public class S11Problem15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 15");
}
}import java.util.*;
public class S11Problem16 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 16");
}
}import java.util.*;
public class S11Problem17 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 17");
}
}import java.util.*;
public class S11Problem18 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 18");
}
}import java.util.*;
/**
* Represents an athlete in the high school's sports team management system.
*/
public class Athlete {
// Private instance variables
/**
* Constructs an Athlete with specified attributes.
*
* @param name The name of the athlete.
* @param grade The grade level (9th, 10th, 11th, 12th).
* @param sport The sport the athlete participates in.
* @param position The position in the sport (e.g., forward, goalkeeper).
* @param height The height of the athlete in inches.
* @param weight The weight of the athlete in pounds.
*/
// Accessor (getter) methods
/**
* Gets the athlete's name.
*
* @return The name of the athlete.
*/
/**
* Gets the athlete's grade level.
*
* @return The grade level of the athlete.
*/
/**
* Gets the sport the athlete participates in.
*
* @return The sport of the athlete.
*/
/**
* Gets the athlete's position in the sport.
*
* @return The position of the athlete.
*/
/**
* Gets the height of the athlete.
*
* @return The height in inches.
*/
/**
* Gets the weight of the athlete.
*
* @return The weight in pounds.
*/
// Mutator (setter) methods
/**
* Sets the athlete's name.
*
* @param name The new name of the athlete.
*/
/**
* Sets the athlete's grade level.
*
* @param grade The new grade level.
*/
/**
* Sets the sport the athlete participates in.
*
* @param sport The new sport.
*/
/**
* Sets the athlete's position.
*
* @param position The new position.
*/
/**
* Sets the height of the athlete.
*
* @param height The new height in inches.
*/
/**
* Sets the weight of the athlete.
*
* @param weight The new weight in pounds.
*/
/**
* Returns a string representation of the athlete.
*
* @return A string containing all attributes of the athlete.
*/
@Override
public String toString() {
}
/**
* The main method tests the Athlete class by creating instances and using
* its methods.
*
* @param args Command-line arguments (not used).
*/
public static void main(String[] args) {
// Creating athlete objects
// Displaying initial details
// Modifying attributes using setters
// Displaying updated details
}
}
/**
* The HighSchoolStudent class represents a high school student with a name.
* It includes a static counter to track the number of students created.
*/
public class HighSchoolStudent {
// instance variable
// static instance variable
/**
* Constructs a new HighSchoolStudent with the given name.
* Increments the student counter upon creation.
*
* @param name The name of the student.
*/
/**
* Returns the total number of students created.
*
* @return the total number of students created.
*/
/**
* Returns a string representation of the student.
*
* @return A string containing the student's name.
*/
public String toString() {
return "Student Name: " + name;
}
}/**
* The SchoolMember class represents a student in a school with a name and grade level.
*/
public class SchoolMember {
/** The name of the student. */
private String name;
/** The grade level of the student (9, 10, 11, or 12). */
private int gradeLevel;
/** A static counter to track the total number of students. */
public static int memberCounter = 0;
// TODO: Declare additional static variables to track students in each grade level.
/**
* Constructs a SchoolMember object with a name and grade level.
* Increments the total member counter and the respective grade counter.
*
* @param name The name of the student.
* @param gradeLevel The grade level of the student (9-12).
*/
public SchoolMember(String name, int gradeLevel) {
this.name = name;
this.gradeLevel = gradeLevel;
memberCounter++;
// TODO: Update the appropriate grade level counter.
}
/**
* Returns the grade level of the student.
*
* @return The grade level of the student.
*/
public int getGradeLevel() {
// TODO: Implement this method
return 0; // Placeholder
}
/**
* Prints the total number of school members and breakdown by grade.
*/
public static void printMemberCounter() {
System.out.println("Total members: " + memberCounter);
// TODO: Print the number of students in each grade level.
}
/**
* Returns a string representation of the student.
*
* @return A string containing the student's name and grade level.
*/
public String toString() {
return "Student Name: " + name + ", Grade Level: " + gradeLevel;
}
/**
* The main method for testing.
*
* @param args Command-line arguments (not used).
*/
public static void main(String[] args) {
// TODO: Create at least 3 students with different grade levels
// TODO: Call printMemberCounter() to display the counts
}
}
/**
* The Scoreboard class keeps track of scores in a two-team game where teams alternate turns.
* During a turn, a team makes one or more plays. Each play can score points and the team's
* turn continues, or the play can fail (score 0 points) and the team's turn ends.
*/
public class Scoreboard {
// TODO: Instance variables
/**
* Constructs a new Scoreboard object for tracking scores between two teams.
* The game always begins with team 1 as the active team.
*
* @param team1 the name of team 1
* @param team2 the name of team 2
*/
// TODO: Implement Constructor
/**
* Records a play in the game. If points are scored (parameter > 0), the active team's
* score is updated and that team remains active. If the play fails (parameter = 0),
* the active team's turn ends and the inactive team becomes active.
*
* @param points the number of points scored on this play (0 if the play failed)
* Precondition: points ≥ 0
*/
// Implement this method
/**
* Returns a string containing the current state of the game in the format:
* "team1Score-team2Score-activeTeamName"
* For example: "0-0-Red" or "1-3-Blue"
*
* @return a string representing the current game state
*/
// TODO: Implemenent this method
}
public class MeanGreeter extends Greeter {
@Override // Compiler will verify this actually overrides a method
// greet method with no parameters
// greet method with one parameter
}class SocialMediaUser {
private String username;
private String platform;
// constructor
// introduce method
public void introduce() {
}
// Getter methods
public String getUsername() {
return username;
}
public String getPlatform() {
return platform;
}
}
class TeenInfluencer extends SocialMediaUser {
private String contentNiche;
private int followerCount;
// constructor
@Override
public void introduce() {
}
// Helper method to format follower count (e.g., 1500 -> 1.5K)
private String formatFollowerCount(int count) {
if (count >= 1000000) {
return String.format("%.1fM", count / 1000000.0);
} else if (count >= 1000) {
return String.format("%.1fK", count / 1000.0);
} else {
return String.valueOf(count);
}
}
// Helper method to add a catchy tagline based on content niche
private void addTagline() {
switch (contentNiche.toLowerCase()) {
case "gaming":
System.out.println("Let's get this win! #GamerLife");
break;
case "fashion":
System.out.println("Serving looks 24/7! #StyleIcon");
break;
case "music":
System.out.println("Dropping beats and making waves! #MusicLife");
break;
case "fitness":
System.out.println("No pain, no gain! #FitCheck");
break;
default:
System.out.println("Don't forget to like and subscribe! #ContentCreator");
}
}
}
public class SocialMediaDemo {
public static void main(String[] args) {
// Create a regular social media user
// Create some teen influencers with different niches
// Test the introduce methods
}
}public class Customer
{
private String name;
private String address;
public Customer(String n, String a)
{
name = n;
address = a;
}
public String toString()
{
return "Name: " + name + "\nAddress: " + address;
}
public static void main(String[] args)
{
Customer c = new Customer("Fran Santiago", "123 Main St., Anytown, USA");
System.out.println(c);
// Uncomment these to test OnlineCustomer
// OnlineCustomer c2 = new OnlineCustomer("Jasper Smith",
// "456 High St., Anytown, USA", "[email protected]");
// System.out.println(c2);
}
}
// Complete the OnlineCustomer class to inherit from Customer
// It should have an email attribute,
// a constructor with 3 arguments (name, address, email) that uses the super
// constructor,
// and an overridden toString() method that calls the super toString() method
// and then prints "\nEmail:" and the email variable.
class OnlineCustomer
{
}// Shape class
class Shape {
// Method to describe the relationship between two shapes
// Overriding toString() method
}
// Square class
class Square extends Shape {
// Overriding toString() method
}
// Rectangle class
class Rectangle extends Shape {
// Overriding toString() method
}
// Main class to demonstrate the relationship method
public class MoreShapesDemo {
public static void main(String[] args) {
// Creating Shapes
// Array of Shapes
// Demonstrating the relationships
}
}import java.util.*;
/**
* This code is based upon code in
* https://practiceit.cs.washington.edu/problem/view/bjp4/chapter9/e10-DiscountBill
*/
// Class representing an item with a name and price
class Item {
private String name; // Name of the item
private double price; // Price of the item
// Default constructor initializing item with empty name and price 0.0
public Item() {
this.name = "";
this.price = 0.0;
}
// Constructor that initializes item with given name and price
public Item(String name, double price) {
this.name = name;
this.price = price;
}
// Method to get the price of the item
public double getPrice() {
return price;
}
// Method to format a double value to a currency string
public String valueToString(double value) {
String result = "" + Math.abs(value);
if (result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
// Overriding toString() to return the item name and price as a string
public String toString() {
return name + " " + valueToString(price);
}
}
// DiscountedItem class inheriting from Item
class DiscountedItem extends Item {
// Instance variable for the discount amount
// Default constructor initializing discount to 0.0
// Constructor that initializes name, price, and discount
// Call the superclass constructor
// Getter method for discount amount
// Setter method for discount amount
// Overriding toString() to include discount amount formatted as currency
}
// ShoppingCart class to manage a collection of items
class ShoppingCart {
private ArrayList<Item> order; // List to store items
private double total; // Total price of items
private double internalDiscount; // Total discount amount
// Constructor initializing the cart with an empty order list and zero totals
public ShoppingCart() {
order = new ArrayList<Item>();
total = 0.0;
internalDiscount = 0.0;
}
// Method to add an item to the cart and update totals
public void add(Item i) {
order.add(i);
total += i.getPrice();
// Check if the item is a discounted item and update discount
// if (i instanceof DiscountedItem)
// internalDiscount += ((DiscountedItem) i).getDiscount();
}
// Method to print the order details
public void printOrder() {
System.out.println(this);
}
// Overriding toString() to return a formatted order summary
public String toString() {
return discountToString();
}
// Method to format the entire order, including subtotal, discount, and total
public String discountToString() {
return orderToString() + "\nSub-total: " + valueToString(total) + "\nDiscount: " + valueToString(internalDiscount) + "\nTotal: " + valueToString(total - internalDiscount);
}
// Method to format a double value to a currency string
private String valueToString(double value) {
value = Math.rint(value * 100) / 100.0;
String result = "" + Math.abs(value);
if (result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
// Method to build a string representation of all order items
public String orderToString() {
String build = "\nOrder Items:\n";
for (int i = 0; i < order.size(); i++) {
build += " " + order.get(i);
if (i != order.size() - 1) {
build += "\n";
}
}
return build;
}
}
// Main class to demonstrate the ShoppingCart functionality
public class ShoppingCartDemo {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
// Adding regular items to the cart
cart.add(new Item("bread", 3.25));
cart.add(new Item("milk", 2.50));
// Adding discounted items to the cart
// cart.add(new DiscountedItem("ice cream", 4.50, 1.50));
// cart.add(new DiscountedItem("apples", 1.35, 0.25));
// Print the contents of the cart
cart.printOrder();
}
}
import java.util.*;
public class Session8 {
public static void main(String[] main) {
System.out.println("Session 8");
Scanner in = new Scanner(System.in);
// example1 method call
// example2 method call
}
// example1 method definition
public static void example1() {
// add code
}
// example2 method definition
public static void example2() {
// add code
}
}import java.util.*;
public class Session8v2 {
public static void main(String[] args) {
System.out.println("Session 8v2");
// example1 method call
// example2 method call
// example3 method call
// example4 method call
// example5 method call
// example6 method call
// example7 method call
// example8 method call
// example9 method call
// example10 method call
}
// example1 method definition
public static void example1() {
// add code
}
// example2 method definition
public static void example2() {
// add code
}
// example3 method definition
public static void example3() {
Scanner in = new Scanner(System.in);
// add code
}
// example4 method definition
public static void example4() {
Scanner in = new Scanner(System.in);
// add code
}
// example5 method definition
public static void example5() {
Scanner in = new Scanner(System.in);
// add code
}
// example6 method definition
public static void example6() {
Scanner in = new Scanner(System.in);
// add code
}
// example7 method definition
public static void example7() {
Scanner in = new Scanner(System.in);
// add code
}
// example8 method definition
public static void example8() {
Scanner in = new Scanner(System.in);
// add code
}
// example9 method definition
public static void example9() {
Scanner in = new Scanner(System.in);
// add code
}
// example10 method definition
public static void example10() {
Scanner in = new Scanner(System.in);
// add code
}
}
import java.util.*;
public class S8Problem1
{
public static void main(String[] args)
{
System.out.println("Problem 1");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem2
{
public static void main(String[] args)
{
System.out.println("Problem 2");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem3
{
public static void main(String[] args)
{
System.out.println("Problem 3");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem4
{
public static void main(String[] args)
{
System.out.println("Problem 4");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem5
{
public static void main(String[] args)
{
System.out.println("Problem 5");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem6
{
public static void main(String[] args)
{
System.out.println("Problem 6");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem7
{
public static void main(String[] args)
{
System.out.println("Problem 7");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem8
{
public static void main(String[] args)
{
System.out.println("Problem 8");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem9
{
public static void main(String[] args)
{
System.out.println("Problem 9");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem10
{
public static void main(String[] args)
{
System.out.println("Problem 10");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem11
{
public static void main(String[] args)
{
System.out.println("Problem 11");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem12
{
public static void main(String[] args)
{
System.out.println("Problem 10");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem13
{
public static void printRandomResponse()
{
// 1. Get a random number from 1 to 8
// 2. Use if statements to test the random number
// and print out 1 of 8 random responses
}
public static void lucky()
{
// 3. Use Math.random() to toss a coin to choose between 2 choices
// 4. Use an if/else statement to test the random number
// and print out "Lucky!" or else "No Luck!"
}
public static void main(String[] args)
{
String question = "Will it rain tomorrow?";
System.out.println(question);
printRandomResponse();
lucky();
}
}import java.util.*;
public class S8Problem14
{
public static void main(String[] args)
{
System.out.println("Problem 14");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem15
{
public static void main(String[] args)
{
System.out.println("Problem 15");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem16
{
public static void main(String[] args)
{
System.out.println("Problem 16");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem17
{
public static void main(String[] args)
{
System.out.println("Problem 17");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem18
{
public static void main(String[] args)
{
System.out.println("Problem 18");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem19
{
public static void main(String[] args)
{
System.out.println("Problem 19");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class S8Problem20
{
public static void main(String[] args)
{
System.out.println("Problem 20");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class Session10 {
public static void main(String[] args) {
System.out.println("Session 10");
Scanner in = new Scanner(System.in);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
// setup Scanner
System.out.print("Choice: ");
String choice = in.nextLine();
// switch statement
switch(choice) {
case "E1":
example1();
break;
case "E2":
example2();
break;
case "E3":
example3();
break;
case "E4":
example4();
break;
case "E5":
example5();
break;
case "E6":
example6();
break;
case "E7":
example7();
break;
case "E8":
example8();
break;
case "E9":
example9();
break;
case "E10":
example10();
break;
case "E11":
example11();
break;
case "E12":
example12();
break;
default:
System.out.println("Invalid choice");
break;
}
}
// example1 method definition
public static void example1() {
Scanner in = new Scanner(System.in);
System.out.print("A: ");
boolean A = in.nextBoolean();
System.out.print("B: ");
boolean B = in.nextBoolean();
// add new code
}
// example2 method definition
public static void example2() {
Scanner in = new Scanner(System.in);
System.out.print("isWeekDay: ");
boolean isWeekDay = in.nextBoolean();
System.out.print("isWorkHours: ");
boolean isWorkHours = in.nextBoolean();
// Original
// Equivalent (using DeMorgan's)
}
// example3 method definition
public static void example3() {
Scanner in = new Scanner(System.in);
System.out.print("A: ");
boolean A = in.nextBoolean();
System.out.print("B: ");
boolean B = in.nextBoolean();
// add new code
}
// example4 method definition
public static void example4() {
Scanner in = new Scanner(System.in);
System.out.print("isCold: ");
boolean isCold = in.nextBoolean();
System.out.print("isRainy: ");
boolean isRainy = in.nextBoolean();
// Original
// Equivalent (using DeMorgans)
}
// example5 method definition
public static void example5() {
Scanner in = new Scanner(System.in);
System.out.print("isRaining: ");
boolean isRaining = in.nextBoolean();
System.out.print("isWindy: ");
boolean isWindy = in.nextBoolean();
// add new code
}
// example6 method definition
public static void example6() {
Scanner in = new Scanner(System.in);
System.out.print("x: ");
int x = in.nextInt();
System.out.print("y: ");
int y = in.nextInt();
// Equality comparison
// Equivalent Negation
}
// example7 method definition
public static void example7() {
System.out.println("Example 7");
Scanner in = new Scanner(System.in);
System.out.print("x: ");
int x = in.nextInt();
System.out.print("y: ");
int y = in.nextInt();
// Greater than comparison
// Equivalent Negation
}
// example8 method definition
public static void example8() {
System.out.println("Example 8");
Scanner in = new Scanner(System.in);
System.out.print("x: ");
int x = in.nextInt();
System.out.print("y: ");
int y = in.nextInt();
// Less than comparison
// Equivalent Negation
}
// example9 method definition
public static void example9() {
System.out.println("Example 9");
Scanner in = new Scanner(System.in);
System.out.print("x: ");
int x = in.nextInt();
System.out.print("y: ");
int y = in.nextInt();
// Greater than or equal comparison
// Equivalent Negation
}
// example10 method definition
public static void example10() {
System.out.println("Example 10");
Scanner in = new Scanner(System.in);
System.out.print("x: ");
int x = in.nextInt();
System.out.print("y: ");
int y = in.nextInt();
// Less than or equal comparison
// Equivalent Negation
}
// example11 method definition
public static void example11() {
Scanner in = new Scanner(System.in);
System.out.print("A: ");
double A = in.nextDouble();
System.out.print("B: ");
double B = in.nextDouble();
// add code
}
// example12 method definition
public static void example12() {
}
}import java.util.*;
public class S10Problem1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 1");
boolean userLoggedIn = in.nextBoolean();
boolean hasPermission = in.nextBoolean();
// Original
if (!userLoggedIn || !hasPermission) {
System.out.println("Access denied.");
} else {
System.out.println("Access granted.");
}
// Simplify using De Morgan's Laws
}
}import java.util.*;
public class S10Problem2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 2");
boolean isMember = in.nextBoolean();
boolean hasActiveSubscription = in.nextBoolean();
// Original
if (!isMember || !hasActiveSubscription) {
System.out.println("Access denied. Please check your membership or subscription.");
} else {
System.out.println("Access granted. Welcome!");
}
// Simplify using De Morgan's Laws
}
}import java.util.*;
public class S10Problem3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 3");
boolean isLoggedIn = in.nextBoolean();
boolean isPaidUser = in.nextBoolean();
// Original
if (!isLoggedIn || !isPaidUser) {
System.out.println("Please log in or purchase a subscription.");
} else {
System.out.println("Welcome to the premium service!");
}
// Simplify using De Morgan's Laws
}
}import java.util.*;
public class S10Problem4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 4");
boolean isHungry = in.nextBoolean();
boolean isThirsty = in.nextBoolean();
// Original
if (!(isHungry || isThirsty)) {
System.out.println("Satisfied");
} else {
System.out.println("Not satisfied");
}
// Simplify using De Morgan's Laws
}
}import java.util.*;
public class S10Problem5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 5");
boolean isWeekend = in.nextBoolean();
boolean isHoliday = in.nextBoolean();
// Original
if (!(isWeekend || isHoliday)) {
System.out.println("Have Work");
} else {
System.out.println("Don't have work");
}
// Simplify using De Morgan's Laws
}
}import java.util.*;
public class S10Problem6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 6");
boolean isOpenLate = in.nextBoolean();
boolean isCrowded = in.nextBoolean();
// Original
if (!(isOpenLate || isCrowded)) {
System.out.println("Perfect time");
} else {
System.out.println("Not the perfect time");
}
// Simplify using De Morgan's Laws
}
}import java.util.*;
public class S10Problem7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 7");
}
}import java.util.*;
public class S10Problem8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 8");
}
}import java.util.*;
public class S10Problem9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 9");
}
}import java.util.*;
public class S10Problem10 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 10");
}
}import java.util.*;
public class S10Problem11 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 11");
}
}import java.util.*;
public class S10Problem12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 12");
}
}import java.util.*;
public class Week18 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 18" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
System.out.println("Q - Quit");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
ArrayList<Integer> list1 = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
list1.add(i);
}
list1.add(5);
// list2
ArrayList<Integer> list2 = new ArrayList<>();
for (int i = 0; i <= 5; i++) {
list2.add(i);
}
// result1
// result2
break;
case "E3":
System.out.println("Example 3");
// list3
ArrayList<Double> list3 = new ArrayList<>();
for (int i = 0; i <= 5; i++) {
list3.add((double) i);
}
for (int i = 4; i >= 1; i--) {
list3.add((double) i);
}
// list4
ArrayList<Double> list4 = new ArrayList<>();
for (int i = 0; i <= 10; i++) {
list4.add(Math.random() * 10);
}
// result3
// result4
break;
case "E4":
System.out.println("Example 4");
int[] arr1 = { 3, -2, 9, 38, -23 };
// sequentialSearch Tests
System.out.println("Tests of Array sequentialSearch");
break;
case "E5":
System.out.println("Example 5");
ArrayList<Integer> list5 = new ArrayList<Integer>();
list5.add(3);
list5.add(-2);
list5.add(9);
list5.add(38);
list5.add(-23);
// sequentialSearch ArrayList Tests
System.out.println("Tests of ArrayList sequentialSearch");
break;
case "E6":
System.out.println("Example 6");
String[] arr2 = { "blue", "red", "purple", "green" };
// test when the target is in the array
// test when the target is not in the array
break;
case "E7":
System.out.println("Example 7");
int[] arr3 = { -20, 3, 15, 81, 432 };
// test when the target is in the middle
// test when the target is the first item in the array
// test when the target is in the array - last
// test when the target is not in the array
break;
case "E8":
int[] arr4 = { 3, 86, -20, 14, 40 };
System.out.println("Original: " + Arrays.toString(arr4));
selectionSort(arr4);
System.out.println("Sorted: " + Arrays.toString(arr4));
break;
case "E9":
int[] arr5 = { 3, 86, -20, 14, 40 };
System.out.println("Original: " + Arrays.toString(arr5));
insertionSort(arr5);
System.out.println("Sorted: " + Arrays.toString(arr5));
break;
case "Q":
System.out.println("Quitting..!");
break;
}
}
// example1 method
public static void example1() {
// create ArrayList of 0 - 5
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
arr.add(i);
}
// intention is to remove every other element
for (int i = 0; i < arr.size(); i++) {
if (i % 2 == 0) {
System.out.println("Removing element " + i + " : " + arr.get(i));
arr.remove(i);
}
}
// print the array
System.out.println(arr);
}
// hasConsecutiveDuplicates method
public static boolean hasConsecutiveDuplicates(ArrayList<Integer> list) {
// Compare consecutive elements
// Duplicate found
return false; // otherwise return false
}
// hasDuplicates method
public static boolean hasDuplicates(ArrayList<Double> list) {
// Compare each element with every element after it
// Found a duplicate
// No duplicates found
return false;
}
// sequentialSearch Array
public static int sequentialSearch(int[] elements, int target) {
return -1;
}
// sequentialSearch ArrayList
public static int sequentialSearch(ArrayList<Integer> elements, int target) {
return -1;
}
// sequentialSearch on an Array of Strings
public static int sequentialSearch(String[] elements, String target) {
return -1;
}
// binarySearch method
public static int binarySearch(int[] elements, int target) {
int left = 0;
int right = elements.length - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (target < elements[middle]) {
right = middle - 1;
} else if (target > elements[middle]) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
/**
* Sorts an array of integers in ascending order using the selection sort
* algorithm.
*
* @param elements The array of integers to be sorted. The array is modified in
* place,
* and the sorted array is the same as the input array with its
* elements rearranged.
*/
public static void selectionSort(int[] elements) {
for (int j = 0; j < elements.length - 1; j++) {
int minIndex = j;
for (int k = j + 1; k < elements.length; k++) {
if (elements[k] < elements[minIndex]) {
minIndex = k;
}
}
int temp = elements[j];
elements[j] = elements[minIndex];
elements[minIndex] = temp;
System.out.println(Arrays.toString(elements));
}
}
/**
* Sorts an array of integers in ascending order using the insertion sort
*
* @param elements The array of integers to be sorted. The array is modified in
* place,
* meaning the sorted array is the same as the input array with
* its elements rearranged.
*/
public static void insertionSort(int[] elements) {
for (int j = 1; j < elements.length; j++) {
int temp = elements[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) {
elements[possibleIndex] = elements[possibleIndex - 1];
possibleIndex--;
}
elements[possibleIndex] = temp;
System.out.println(Arrays.toString(elements));
}
}
}import java.util.ArrayList;
public class WordChecker
{
/**
* Initialized in the constructor and contains no null elements.
*/
private ArrayList<String> wordList;
/**
* Constructor that initializes wordList.
* @param words the list of words for this WordChecker
*/
public WordChecker(ArrayList<String> words)
{
wordList = words;
}
/**
* Returns true if each element of wordList (except the first) contains
* the previous element as a substring and returns false otherwise,
* as described in part (a).
*
* Precondition: wordList contains at least two elements.
* Postcondition: wordList is unchanged.
*/
public boolean isWordChain()
{
// TODO: Implement part (a)
return false; // placeholder return
}
/**
* Returns an ArrayList<String> based on strings from wordList that start
* with target, as described in part (b). Each element of the returned ArrayList
* has had the initial occurrence of target removed.
*
* Postconditions: wordList is unchanged.
* Items appear in the returned list in the same order as they appear in wordList.
*
* @param target the substring to match at the start of each word
* @return an ArrayList of words with the initial occurrence of target removed
*/
public ArrayList<String> createList(String target)
{
// TODO: Implement part (b)
return new ArrayList<String>(); // placeholder return
}
/**
* Test the WordChecker class within the same file.
*/
public static void main(String[] args)
{
// Sample data
ArrayList<String> words = new ArrayList<>();
words.add("an");
words.add("band");
words.add("band");
words.add("abandon");
// Create a WordChecker object
WordChecker checker = new WordChecker(words);
// Test isWordChain (part a)
System.out.println("isWordChain? " + checker.isWordChain());
// Test createList (part b)
System.out.println("createList(\"ban\"): " + checker.createList("ban"));
}
}
apple
banana
cat
dog
elephant
fish
grape
house
igloo
jungle
kangaroo
lemon
monkey
nest
orange
penguin
queen
rabbit
snake
tiger
umbrella
violin
whale
xylophone
yacht
zebraimport java.io.*;
import java.nio.file.*;
import java.util.*;
public class SpellCheckerSearch
{
private ArrayList<String> dictionary;
/* Constructor populates the dictionary ArrayList from the file dictionary.txt*/
public SpellCheckerSearch() throws IOException
{
List<String> lines = Files.readAllLines(Paths.get("dictionary.txt"));
dictionary = new ArrayList<String>(lines);
}
/**
* Write a linearSearch(word) method that finds a word
* in the ArrayList dictionary. It should also keep
* a count of the number of words checked.
*
* @param String word to be found in elements.
* @return a count of how many words checked before returning.
*/
public int linearSearch(String word)
{
return -1;
}
/**
* Write a binarySearch(word) method that finds the word
* in the ArrayList dictionary. It should also keep
* a count of the number of words checked.
*
* @param String word to be found in elements.
* @return a count of how many words checked before returning.
*/
public int binarySearch(String word)
{
return -1;
}
public void print() {
System.out.println("index\tword");
for (int i = 0; i < dictionary.size(); i++) {
System.out.println(i + "\t" + dictionary.get(i));
}
}
public static void main(String[] args) throws IOException
{
SpellCheckerSearch checker = new SpellCheckerSearch();
checker.print();
String word = "zebra"; // example
int i = checker.linearSearch(word);
System.out.println("Linear search steps for " + word + " = " + i);
int count = checker.binarySearch(word);
System.out.println("Binary search steps for " + word + " = " + count);
}
}
import java.util.*;
public class Week13 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 13" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
case "E5":
System.out.println("Example 5");
example5();
break;
case "E6":
System.out.println("Example 6");
example6();
break;
case "E7":
System.out.println("Example 7");
example7();
break;
default:
System.out.println("Invalid choice");
}
}
// example1 method
public static void example1() {
// Create two points
// Display the points
}
// example2 method
public static void example2() {
// Create two points
// Display the points
// Swap the coordinates
// Display the points
}
// example3 method
public static void example3() {
}
// example4 method
public static void example4() {
}
// example5 method
public static void example5() {
// Create coins for two players
// Each player flips their coin
// Show the results of the flips
// Determine the winner
}
// example6 method
public static void example6() {
// Using the default constructor
}
// example7 method
public static void example7() {
// Using the parameterized constructor
}
}
/**
* The Point class represents a point in 2D space
* with x and y coordinates.
*/
public class Point {
// instance variables
/**
* Constructs a Point with specified x and y coordinates.
*
* @param x The x-coordinate of the point.
* @param y The y-coordinate of the point.
*/
/**
* Sets the x-coordinate of the point.
*
* @param x The new x-coordinate.
*/
/**
* Sets the y-coordinate of the point.
*
* @param y The new y-coordinate.
*/
/**
* Gets the x-coordinate of the point.
*
* @return The x-coordinate.
*/
/**
* Gets the y-coordinate of the point.
*
* @return The y-coordinate.
*/
/**
* Returns a string representation of the point.
*
* @return A string in the format "(x, y)".
*/
@Override
}/**
* The Coin class represents a coin with two sides: Heads and Tails.
* It provides methods to flip the coin, check if it's heads,
* and retrieve the current state as a string.
*/
public class Coin {
// instance variables
// 0 for Heads, 1 for Tails
/**
* Initializes the coin by flipping it to set a random initial state.
*/
/**
* Flips the coin to randomly set the state to Heads or Tails.
*/
/**
* Checks if the current state of the coin is Heads.
*
* @return true if the coin is heads, false otherwise.
*/
/**
* Returns a string representation of the current state of the coin.
*
* @return "Heads" if the coin is heads, "Tails" otherwise.
*/
@Override
}public class Book {
// Properties
// Constructor
// Getters
// Method to mark the book as read
// Method to provide a string representation of the book
@Override
// Main method to test the Book class
public static void main(String[] args) {
// Create three instances of your favorite books
// Print the title, author, and pages for each book
// Mark all books as read
// Print each book's string representation
}
}
/**
* The Ingredient class represents an ingredient in a recipe or inventory.
* Each ingredient has a name, an amount, a unit of measurement, and an
* indication of whether it is organic.
*/
public class Ingredient {
// Instance variables
private String name;
private double amount;
private String unit;
private boolean organic;
/**
* Constructs a new Ingredient with the specified properties.
*
* @param name The name of the ingredient.
* @param amount The quantity of the ingredient.
* @param unit The unit of measurement for the ingredient.
* @param organic True if the ingredient is organic; false otherwise.
*/
public Ingredient(String name, double amount, String unit, boolean organic) {
this.name = name;
this.amount = amount;
this.unit = unit;
this.organic = organic;
}
/**
* Returns the name of the ingredient.
*
* @return The name of the ingredient.
*/
public String getName() {
return name;
}
/**
* Returns the amount of the ingredient.
*
* @return The quantity of the ingredient.
*/
public double getAmount() {
return amount;
}
/**
* Returns the unit of measurement for the ingredient.
*
* @return The unit of measurement (e.g., "cups", "grams").
*/
public String getUnit() {
return unit;
}
/**
* Checks if the ingredient is organic.
*
* @return True if the ingredient is organic, false otherwise.
*/
public boolean isOrganic() {
return organic;
}
}/**
* The Recipe class represents a recipe with a name, a main ingredient,
* a secondary ingredient, and a cooking time. It provides methods to calculate
* the cost of the recipe, check if the recipe is fully organic, and determine
* the nutritional rating based on ingredient properties.
*/
public class Recipe {
// Instance variables
private Ingredient mainIngredient;
private Ingredient secondaryIngredient;
private String name;
private int cookingTime;
/**
* Constructs a new Recipe with the specified name, ingredients, and cooking
* time.
* If invalid parameters are provided, default values are used instead.
*
* @param name The name of the recipe.
* @param main The main ingredient of the recipe.
* @param secondary The secondary ingredient of the recipe.
* @param cookingTime The cooking time in minutes. If less than or equal to
* zero, defaults to Integer.MIN_VALUE.
*/
public Recipe(String name, Ingredient main, Ingredient secondary, int cookingTime) {
this.name = name.trim();
this.mainIngredient = main;
this.secondaryIngredient = secondary;
// Validate and assign cooking time
if (cookingTime <= 0) {
this.cookingTime = Integer.MIN_VALUE;
} else {
this.cookingTime = cookingTime;
}
}
/**
* Calculates the total cost of the recipe.
*
* @return The total cost of the recipe.
*/
public double getCost() {
double baseCost = mainIngredient.getAmount() * 2.5 +
secondaryIngredient.getAmount() * 1.5;
if (isFullyOrganic()) {
baseCost *= 1.5; // Organic premium
}
return baseCost;
}
/**
* Checks if the recipe is fully organic.
*
* @return True if both ingredients are organic, false otherwise.
*/
public boolean isFullyOrganic() {
return mainIngredient.isOrganic() &&
secondaryIngredient.isOrganic();
}
/**
* Determines the nutritional rating of the recipe.
*
* @return The nutritional rating ("A", "B", or "C").
*/
public String getNutritionalRating() {
if (isFullyOrganic()) {
return "A";
} else if (mainIngredient.isOrganic() || secondaryIngredient.isOrganic()) {
return "B";
} else {
return "C";
}
}
/**
* Returns the cooking time for the recipe.
*
* @return The cooking time in minutes.
*/
public int getCookingTime() {
return cookingTime;
}
/**
* Returns a string representation of the recipe.
*
* @return A string containing the recipe details.
*/
@Override
public String toString() {
String recipeString = "Recipe: " + name + "\n";
recipeString += "Main Ingredient: " + mainIngredient.getName() + "\n";
recipeString += "Secondary Ingredient: " + secondaryIngredient.getName() + "\n";
recipeString += "Rating: " + getNutritionalRating() + "\n";
recipeString += "Cooking Time: " + getCookingTime() + " minutes";
return recipeString;
}
}
/**
* The MealPlan class represents a weekly meal plan, including two recipes,
* the total number of servings, and methods to calculate cost and check if
* the plan is fully organic.
*/
public class MealPlan {
/**
* Constructs a MealPlan with the specified name, recipes, and servings.
* If invalid parameters are provided, default values are used.
*
* @param name The name of the meal plan.
* @param breakfastRecipe The breakfast recipe.
* @param lunchRecipe The breakfast recipe.
* @param dinnerRecipe The dinner recipe.
*/
/**
* Calculates the total cost of the meal plan for the week.
*
* @return The total cost of the meal plan.
*/
/**
* Checks if the meal plan is fully organic.
*
* @return True if both recipes are fully organic, false otherwise.
*/
/**
* Returns a summary of the meal plan, including its name, total cost,
* and organic status.
*
* @return A summary string of the meal plan.
*/
public static void main(String[] args) {
// breakfast recipe
// lunch recipe
// dinner recipe
// Valid meal plan
}
}
import java.util.*;
/**
* The Calculator class provides basic arithmetic operations.
* @author CGA Student
*/
public class Calculator {
/**
* Adds two integers.
*
* @param a the first integer
* @param b the second integer
* @return the sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
/**
* Main method.
*
* @param args command line arguments (not used)
*/
public static void main(String[] args) {
Calculator calculator = new Calculator();
// Example
System.out.println("Addition: " + calculator.add(10, 5));
// Ask the user for two numbers
}
}
import java.util.*;
public class Session5 {
public static void main(String[] main) {
System.out.println("Session 5");
// example1 method call
// example2 method call
// example3 method call
// example4 method call
}
// example1 method definition
// example2 method definition
// example3 method definition
// example4 method definition
}
public class NumberHelper {
/**
* Doubles the given number.
* Formula: result = num * 2
*
* @param num the number to double
* @return the result of num multiplied by 2
*/
/**
* Finds the average of two numbers.
* Formula: average = (a + b) / 2.0
*
* @param a the first number
* @param b the second number
* @return the average of a and b as a double
*/
public static void main(String[] args) {
System.out.println("Class Methods Example");
// call Class methods
}
}import java.util.*;
public class S5Problem1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 1");
System.out.print("Enter the length of the rectangular solid: ");
System.out.print("Enter the width of the rectangular solid: ");
System.out.print("Enter the height of the rectangular solid: ");
// call Rectangular Solid method
System.out.println("Volume of the Rectangular Solid: ");
}
// define Volume of a Rectangular Solid method
}import java.util.*;
public class S5Problem2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 2");
System.out.print("Enter the semi-axis a of the ellipsoid: ");
System.out.print("Enter the semi-axis b of the ellipsoid: ");
System.out.print("Enter the semi-axis c of the ellipsoid: ");
// call Ellipsoid method
System.out.println("Volume of the Ellipsoid: ");
}
// define Volume of a Ellipsoid method
}import java.util.*;
public class S5Problem3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 3");
System.out.print("Enter the radius of the circular base of the cylinder: ");
System.out.print("Enter the height of the cylinder: ");
// call Cylinder method
System.out.println("Volume of the Cylinder: ");
}
// define Volume of a Cylinder method
}import java.util.*;
public class S5Problem4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 4");
System.out.print("Enter the radius of the cone's base: ");
System.out.print("Enter the height of the cone: ");
// call Cone method
System.out.println("Volume of the Cone: ");
}
// define Volume of a Cone method
}import java.util.*;
public class S5Problem5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 5");
System.out.print("Enter the length of the rectangular pyramid's base: ");
System.out.print("Enter the width of the rectangular pyramid's base: ");
System.out.print("Enter the height of the rectangular pyramid: ");
// call Rectangular Pyramid method
System.out.println("Volume of the Rectangular Pyramid: ");
}
// define Volume of a Rectangular Pyramid method
}/**
* The AreaCalculator class provides static methods
* to calculate the area of various 2D shapes.
*
* All methods use standard geometric formulas and return
* a double value representing the calculated area.
*
* Author: Your Name
* Date: 2025-10-17
*/
public class AreaCalculator {
/**
* Calculates the area of a rectangle.
* @param l the length of the rectangle
* @param w the width of the rectangle
* @return the area of the rectangle
*/
/**
* Calculates the area of a triangle.
* @param b the base of the triangle
* @param h the height of the triangle
* @return the area of the triangle
*/
/**
* Calculates the area of a circle.
* @param r the radius of the circle
* @return the area of the circle
*/
/**
* Calculates the area of a trapezoid.
* @param b1 the length of the first base
* @param b2 the length of the second base
* @param h the height of the trapezoid
* @return the area of the trapezoid
*/
/**
* Calculates the area of a parallelogram.
* @param b the base of the parallelogram
* @param h the height of the parallelogram
* @return the area of the parallelogram
*/
/**
* Calculates the area of a square.
* @param s the length of one side
* @return the area of the square
*/
/**
* Calculates the area of a rhombus.
* @param d1 the length of the first diagonal
* @param d2 the length of the second diagonal
* @return the area of the rhombus
*/
/**
* Calculates the area of an ellipse.
* @param a the semi-major axis
* @param b the semi-minor axis
* @return the area of the ellipse
*/
public static void main(String[] args) {
System.out.println("Area Calculator");
// System.out.println("Rectangle: " + AreaCalculator.rectangle(5, 3));
// System.out.println("Triangle: " + AreaCalculator.triangle(6, 4));
// System.out.println("Circle: " + AreaCalculator.circle(2));
// System.out.println("Trapezoid: " + AreaCalculator.trapezoid(3, 5, 4));
// System.out.println("Parallelogram: " + AreaCalculator.parallelogram(8, 3));
// System.out.println("Square: " + AreaCalculator.square(4));
// System.out.println("Rhombus: " + AreaCalculator.rhombus(6, 8));
// System.out.println("Ellipse: " + AreaCalculator.ellipse(5, 3));
}
}
import java.util.*;
public class S5Problem6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 6");
// Define the coordinates of two points
// Calculate the differences in x and y coordinates
// Calculate the square of the distance using Math.pow
// Get the actual distance using Math.sqrt
// Output the results
}
}import java.util.*;
public class S5Problem7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 7");
// Define the coordinates of two points in 3D space
// Calculate the differences between the corresponding coordinates
// Use Math.abs to convert differences to absolute values
// Calculate the square of the distance using Math.pow
// Calculate the actual distance using Math.sqrt
// Print out the results
}
}import java.util.*;
public class S5Problem8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 8");
// 1. Use Math.random() to generate 3 integers from 0-40 (not
// including 40) and print them out.
// 2. Calculate the number of combinations to choose 3 numbers between
// 0-40 (not including 40) using Math.pow() and print it out.
// For example, Math.pow(10,2) is 10^2 and the number of permutations
// to choose 2 numbers between 0-9.
}
}import java.util.*;
public class S5Problem9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 9");
}
}import java.util.*;
public class S5Problem10 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Problem 10");
}
}/**
* The GradeCalculator class calculates a student's final course grade
* by combining weighted category scores (homework, quizzes, and exam)
* and adding extra credit
*/
public class GradeCalculator {
/**
* The main method displays a formatted grade report.
*/
public static void main(String[] args) {
System.out.println("===== GRADE CALCULATOR =====\n");
System.out.println("AP Computer Science A - Term Grade\n");
// Ask the user for their overall assignment grade
// Ask the user for their overall quiz grade
// Ask the user for their end of term grade
// Display weighted scores
System.out.println("Assignments 60%): ");
System.out.println("Quizzes (30%): ");
System.out.println("End of Term Exam (10%): ");
// Calculate total grade
System.out.println("\nBase Grade: ");
// Ask the number of points to add for extra credit
System.out.println("After Extra Credit: ");
}
/**
* Calculates the weighted score for a given category.
*
* @param score the percentage score for the category (0–100)
* @param weight the weight of the category as a decimal (e.g., 0.20 for 20%)
* @return the weighted score (score × weight)
*/
/**
* Calculates the total grade by summing three category scores.
*
* @param a the first category score
* @param b the second category score
* @param c the third category score
* @return the total of all four category scores
*/
/**
* Adds extra credit points to a total grade.
*
* @param total the current total grade before extra credit
* @param extra the amount of extra credit to add
* @return the final grade after adding extra credit
*/public class Dog {
// A void method that makes the dog bark
// A void method that makes the dog wag its tail
// A void method that makes the dog roll over
}
public class Cat {
// Private instance variable of the cat's name
private String name;
// Private instance variable to track the cat's hunger level
private int hungerLevel;
// Constructor to initialize the name and hunger level
// A void method to feed the cat (decrease hunger level)
// A void method to make the cat play (increase hunger level)
// A void method to display the current hunger level
}
public class Battery {
// Private instance variable to keep track of the battery charge level
private int chargeLevel;
// Constructor to initialize the charge level
// A void method to charge the battery (increase charge level)
// A void method to use the battery (decrease charge level)
// A void method to reset the battery charge level
// A method to display the current charge level
public void displayChargeLevel() {
System.out.println("Current charge level: " + chargeLevel + "%");
}
}public class Greeting {
// Void method with a single parameter
// Void method with two parameters
}
public class Calculator {
// void addNumbers method with two parameters
// void multiplyNumbers method with two parameters
}
public class Song {
public void printTitle(String title) {
}
public void printAuthor(String author) {
}
public void printSong() {
}
public void printVerse() {
}
public void printChorus() {
}
}public class BankAccount {
// private instance variable
// constructors
// methods
}
public class WordMatch {
// instance variable
private String secret;
/**
* Constructor: initializes the secret word
* @param word the secret word
*/
public WordMatch(String word) {
secret = word;
}
/**
* Part (a): Returns a score based on how many times the guess appears in the secret word
* and how long the guess is.
*
* @param guess the guess word
* @return the score
*/
public int scoreGuess(String guess) {
// TODO: Count number of times guess appears in secret
// Multiply count by length of guess
return 0; // placeholder
}
/**
* Part (b): Returns the guess with the highest score
* If two guesses have the same score, returns the one that comes first alphabetically.
*
* @param options an array of guess words
* @return the best guess
*/
public String findBetterGuess(String guess1, String guess2) {
// TODO: Use scoreGuess to compare the two guesses
return ""; // placeholder
}
// You may include a main method to test your class
public static void main(String[] args) {
WordMatch game = new WordMatch("mississippi");
// Example tests (students should add more)
System.out.println(game.scoreGuess("is")); // expected: 8
System.out.println(game.scoreGuess("sip")); // expected: 6
System.out.println(game.findBetterGuess("is", "sip")); // expected: "is"
}
}
import java.util.*;
public class Week19 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 19" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
System.out.println("Q - Quit");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
case "E5":
System.out.println("Example 5");
example5();
break;
case "E6":
System.out.println("Example 6");
example6();
break;
case "E7":
System.out.println("Example 7");
example7();
break;
case "Q":
System.out.println("Quitting..!");
break;
}
}
// example1 method
public static void example1() {
// create a 2D array named ticketInfo
// print the number of rows and columns
}
// example2 method
public static void example2() {
// create 2D array named seatingChart
// assign the array elements
// print the elements
}
// example3 method
public static void example3() {
// 2D array with an initializer list
// Store A: Apple price, Banana price
// Store B: Apple price, Banana price
// Print the prices
}
// example4 method
public static void example4() {
// create a 3x4 matrix with values
int[][] matrix = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
// nested for loop
// Iterates through rows
// Iterates through columns
// enhanced for loop
}
// example5 method
public static void example5() {
// declare 2D array of numbers
int[][] numbers = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
// accumulate the elements
// print the sum
// calculate the average
}
// example6 method
public static void example6() {
// declare 2D array of numbers
int[][] numbers = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// initialize sum, rows and cols
// nested for loops
// Add the element if it is on the first/last row or first/last column
// print the sum
}
// example7 method
public static void example7() {
// declare 2D array of numbers
int[][] data = {
{ 12, 35, 7 },
{ 22, 18, 90 },
{ 42, 67, 55 }
};
// initialize max to the first element
// print the max
}
}
import java.util.*;
public class W19Problem1
{
public static void main(String[] args)
{
System.out.println("Problem 1");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W19Problem2
{
public static void main(String[] args)
{
System.out.println("Problem 2");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W19Problem3
{
public static void main(String[] args)
{
System.out.println("Problem 3");
Scanner in = new Scanner(System.in);
}
}import java.util.*;
public class W19Problem4
{
// Method 1: Compute the sum of the primary diagonal
public static int diagonalSum(int[][] matrix) {
Scanner in = new Scanner(System.in);
System.out.println("1: Right to Left");
System.out.println("2: Left to Right");
System.out.print("Choice: ");
int direction = in.nextInt();
in.nextLine();
// TODO: Implement logic to sum the diagonal elements
return 0; // Placeholder return value
}
// Method 2: Compute the sum of all elements in a given row
public static int rowSum(int[][] matrix, int rowIndex) {
// TODO: Implement logic to sum the elements of the given row
return 0; // Placeholder return value
}
// Method 3: Compute the sum of all elements in a given column
public static int columnSum(int[][] matrix, int colIndex) {
// TODO: Implement logic to sum the elements of the given column
return 0; // Placeholder return value
}
public static void main(String[] args) {
int[][] matrix = {
{4, 7, 1, 8, 2},
{9, 5, 6, 3, 7},
{2, 6, 8, 4, 1},
{1, 3, 9, 7, 5},
{5, 2, 4, 6, 8}
};
// Test diagonal sum
System.out.println("Diagonal Sum: " + diagonalSum(matrix));
// Test row sum (for example, row index 2)
System.out.println("Sum of row 2: " + rowSum(matrix, 2));
// Test column sum (for example, column index 3)
System.out.println("Sum of column 3: " + columnSum(matrix, 3));
}
}// Represents a single piece of candy
public class Candy {
private String flavor;
/** Constructor to initialize candy with a specific flavor */
public Candy(String flavor) {
this.flavor = flavor;
}
/** Returns the flavor of the candy */
public String getFlavor() {
return flavor;
}
@Override
public String toString() {
return flavor; // Useful for debugging
}
}// Represents a box of candy in a 2D array grid
public class BoxOfCandy {
private Candy[][] box; // 2D array of Candy objects or null
/** Constructor to initialize the box */
public BoxOfCandy(Candy[][] box) {
this.box = box;
}
/**
* Moves one piece of candy in column col, if necessary and possible,
* so that the box element in row 0 of column col contains a piece of candy.
* Returns false if there is no piece of candy in column col and returns true
* otherwise.
*/
public boolean moveCandyToFirstRow(int col) {
// Step 1: Check if there is already a candy in the first row of this column.
// Step 2: Search the column from row 1 downwards to find the first candy.
// Step 3: Move the found candy to the first row
// Step 4: Remove the original reference to avoid duplication
// Successfully moved the candy
// Step 5: If no candy was found in the column, return false.
return false;
}
/**
* Removes from box and returns a piece of candy with the specified flavor,
* or returns null if no such piece is found.
*/
public Candy removeNextByFlavor(String flavor) {
// Step 1: Traverse rows from the bottom-most row to the top-most row.
// Step 2: Traverse each row from left to right.
// Step 3: Check if this cell contains a Candy object and if the flavor matches.
// Step 4: Store the candy reference before removing it.
// Step 5: Remove candy from the box by setting the reference to null.
// Step 6: Return the removed candy.
// Step 7: If no matching candy was found, return null.
return null;
}
/** Helper method to print the box for testing */
public void printBox() {
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
if (box[i][j] == null) {
System.out.print("[ ] ");
} else {
System.out.print("[" + box[i][j].getFlavor().substring(0, 2) + "] ");
}
}
System.out.println();
}
System.out.println();
}
/** Main method to test functionality */
public static void main(String[] args) {
Candy[][] testBox = {
{ null, new Candy("Caramel"), null, new Candy("Mint") },
{ null, null, new Candy("Strawberry"), null },
{ new Candy("Chocolate"), new Candy("Lime"), null, new Candy("Vanilla") }
};
BoxOfCandy box = new BoxOfCandy(testBox);
System.out.println("Initial Box:");
box.printBox();
System.out.println("Moving candy to first row in column 2...");
box.moveCandyToFirstRow(2);
box.printBox();
System.out.println("Removing candy with flavor 'Lime'...");
Candy removed = box.removeNextByFlavor("Lime");
System.out.println("Removed: " + (removed != null ? removed.getFlavor() : "None"));
box.printBox();
System.out.println("Removing candy with flavor 'Chocolate'...");
removed = box.removeNextByFlavor("Chocolate");
System.out.println("Removed: " + (removed != null ? removed.getFlavor() : "None"));
box.printBox();
}
}
public class Location {
private int theRow;
private int theCol;
public Location(int r, int c) {
theRow = r;
theCol = c;
}
public int getRow() {
return theRow;
}
public int getCol() {
return theCol;
}
}public class GridPath {
/** Initialized in the constructor with distinct values that never change */
private int[][] grid;
/** Constructor to initialize the grid */
public GridPath(int[][] gridData) {
grid = gridData;
}
/**
* Returns the Location representing a neighbor of the grid element at row and col,
* as described in part (a)
*/
public Location getNextLoc(int row, int col) {
// TODO: Implement this method
return null;
}
/**
* Computes and returns the sum of all values on a path through grid, as described in
* part (b)
*/
public int sumPath(int row, int col) {
// TODO: Implement this method
return 0;
}
}public class GridPathTester {
public static void main(String[] args) {
// Part A
int[][] grid1 = {
{ 12, 3, 4, 13, 5 },
{ 11, 21, 2, 14, 16 },
{ 7, 8, 9, 15, 0 },
{ 10, 17, 20, 19, 1 },
{ 18, 22, 30, 25, 6 },
};
// Part B
int[][] grid2 = {
{ 12, 30, 40, 25, 5 },
{ 11, 3, 22, 15, 43 },
{ 7, 2, 9, 4, 0 },
{ 8, 33, 18, 6, 1 },
};
GridPath gp = new GridPath(grid1);
// Test getNextLoc
System.out.println("Testing getNextLoc:");
Location loc1 = gp.getNextLoc(0, 0);
if (loc1 != null) {
System.out.println("Next location from (0,0): " + loc1.getRow() + ", " + loc1.getCol());
} else {
System.out.println("getNextLoc(0,0) not implemented yet.");
}
Location loc2 = gp.getNextLoc(1, 3);
if (loc2 != null) {
System.out.println("Next location from (1,3): " + loc2.getRow() + ", " + loc2.getCol());
} else {
System.out.println("getNextLoc(1,3) not implemented yet.");
}
Location loc3 = gp.getNextLoc(2, 4);
if (loc3 != null) {
System.out.println("Next location from (2,4): " + loc3.getRow() + ", " + loc3.getCol());
} else {
System.out.println("getNextLoc(2,4) not implemented yet.");
}
Location loc4 = gp.getNextLoc(4, 3);
if (loc4 != null) {
System.out.println("Next location from (4,3): " + loc4.getRow() + ", " + loc4.getCol());
} else {
System.out.println("getNextLoc(4,3) not implemented yet.");
}
// Test sumPath
System.out.println("\nTesting sumPath:");
int sum = gp.sumPath(1, 1);
if (sum != 0) {
System.out.println("Sum from (1,1): " + sum);
} else {
System.out.println("sumPath(1,1) not implemented yet.");
}
}
}
import java.util.*;
/**
* Provides functionalities to manage a theater's seating arrangement, including displaying the seating grid,
* checking seat pricing, purchasing seats, calculating revenue, and determining the percentage of sold seats.
*/
public class TheaterManagement {
/**
* Main method serving as the entry point of the application. It initializes the seating array
* and processes user inputs through a console-based menu using a do-while loop.
*
* @param args command line arguments (not used)
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Create theater seats and prices
int[][] seats = {
};
do {
System.out.println("G - Show Theater Grid");
System.out.println("S - Seat Pricing");
System.out.println("P - Purchase Seat");
System.out.println("R - Revenue");
System.out.println("C - Calculate Sold Seats Percentage");
System.out.println("Q - Quit");
System.out.print("Choice: ");
String choice = in.nextLine().toUpperCase();
switch (choice) {
case "G":
showTheaterGrid(seats);
break;
case "S":
showSeatPricing(seats, in);
break;
case "P":
purchaseSeat(seats, in);
break;
case "R":
showRevenue(seats);
break;
case "C":
showSoldSeatsPercentage(seats);
break;
case "Q":
return; // Exit the program
default:
System.out.println("Invalid choice. Please try again.");
break;
}
} while (true);
}
/**
* Displays the theater seating grid, indicating seat prices and marking purchased seats with an 'X'.
*
* @param seats The 2D array representing the theater seats and their prices or purchase statuses.
*/
private static void showTheaterGrid(int[][] seats) {
}
/**
* Allows the user to check the pricing of a specific seat by entering its row and column numbers.
*
* @param seats The 2D array representing the theater seats and their prices.
* @param in The Scanner object for user input.
*/
private static void showSeatPricing(int[][] seats, Scanner in) {
}
/**
* Processes the purchase of a seat, marking it as sold (0) in the seating array if available.
*
* @param seats The 2D array representing the theater seats and their prices or purchase statuses.
* @param in The Scanner object for user input.
*/
private static void purchaseSeat(int[][] seats, Scanner in) {
}
/**
* Calculates and displays the total revenue generated from the sold seats.
*
* @param seats The 2D array representing the theater seats and their prices or purchase statuses.
*/
private static void showRevenue(int[][] seats) {
}
/**
* Calculates and displays the percentage of seats that have been sold.
*
* @param seats The 2D array representing the theater seats and their prices or purchase statuses.
*/
private static void showSoldSeatsPercentage(int[][] seats) {
}
}public class CombinedTable {
private SingleTable table1;
private SingleTable table2;
public CombinedTable(SingleTable t1, SingleTable t2) {
table1 = t1;
table2 = t2;
}
public boolean canSeat(int num) {
// TODO: Return true if both tables can seat the given number of guests together
return false; // Placeholder
}
public double getDesirability() {
// TODO: Compute and return the desirability based on the formula
return 0.0; // Placeholder
}
}
public class SingleTable {
private int seats;
private double viewQuality;
private boolean cloth;
public SingleTable(int s, double vq, boolean c) {
seats = s;
viewQuality = vq;
cloth = c;
}
public int getNumSeats() {
return seats;
}
public double getViewQuality() {
return viewQuality;
}
public boolean hasTablecloth() {
return cloth;
}
}
public class CombinedTableTester {
public static void main(String[] args) {
// Create two SingleTable objects
SingleTable table1 = new SingleTable(4, 7.5, true);
SingleTable table2 = new SingleTable(6, 6.0, false);
// Create a CombinedTable with table1 and table2
CombinedTable combined = new CombinedTable(table1, table2);
// Test canSeat
System.out.println("Can seat 9 guests: " + combined.canSeat(9)); // Expected: true
System.out.println("Can seat 11 guests: " + combined.canSeat(11)); // Expected: false
// Test getDesirability
System.out.println("Desirability: " + combined.getDesirability());
// Expected: average of 7.5 and 6.0 = 6.75 (no tablecloth on both, so not multiplied)
}
}
import java.util.ArrayList;
public class MemberInfo {
private String name;
private int gradYear;
private boolean hasGoodStanding;
/** Constructs a MemberInfo object for the club member with name, gradYear, and hasGoodStanding */
public MemberInfo(String name, int gradYear, boolean hasGoodStanding) {
this.name = name;
this.gradYear = gradYear;
this.hasGoodStanding = hasGoodStanding;
}
/** Returns the graduation year of the club member. */
public int getGradYear() {
return gradYear;
}
/** Returns true if the member is in good standing and false otherwise. */
public boolean inGoodStanding() {
return hasGoodStanding;
}
/** Optional: Returns the name of the member (useful for debugging or display) */
public String toString() {
return name + " (" + gradYear + ") - Good Standing: " + hasGoodStanding;
}
}
public class ClubMembers {
private ArrayList<MemberInfo> memberList;
/** Constructs an empty list of members */
public ClubMembers() {
memberList = new ArrayList<MemberInfo>();
}
/**
* Adds new club members to memberList, as described in part (a).
* Precondition: names is a non-empty array.
*/
public void addMembers(String[] names, int gradYear) {
// To be implemented
}
/**
* Removes members who have graduated and returns a list of members who have
* graduated and are in good standing, as described in part (b).
*/
public ArrayList<MemberInfo> removeMembers(int year) {
// To be implemented
return null;
}
/** Optional: View members for testing */
public void printMembers() {
for (MemberInfo m : memberList) {
System.out.println(m);
}
}
}
public class ClubTester {
public static void main(String[] args) {
ClubMembers club = new ClubMembers();
// Example addMembers call (to test part a when implemented)
String[] newNames = {"Alice Brown", "Carlos Diaz"};
club.addMembers(newNames, 2024);
// Add more members manually
club.addMembers(new String[]{"Emily Stone"}, 2022);
// Test print
System.out.println("Before removal:");
club.printMembers();
// Test removeMembers call (to test part b when implemented)
ArrayList<MemberInfo> graduated = club.removeMembers(2023);
System.out.println("\nAfter removal:");
club.printMembers();
System.out.println("\nGraduated and in good standing:");
for (MemberInfo m : graduated) {
System.out.println(m);
}
}
}
public class ArrayResizer {
/** Returns true if and only if every value in row r of array2D is non-zero.
* Precondition: r is a valid row index in array2D.
* Postcondition: array2D is unchanged.
*/
public static boolean isNonZeroRow(int[][] array2D, int r) {
// To be implemented in part (a)
return false;
}
/** Returns the number of rows in array2D that contain all non-zero values.
* Postcondition: array2D is unchanged.
*/
public static int numNonZeroRows(int[][] array2D) {
int count = 0;
for (int r = 0; r < array2D.length; r++) {
if (isNonZeroRow(array2D, r)) {
count++;
}
}
return count;
}
/** Returns a new, possibly smaller, two-dimensional array that contains only rows
* from array2D with no zeros, as described in part (b).
* Precondition: array2D contains at least one column and at least one row with no zeros.
* Postcondition: array2D is unchanged.
*/
public static int[][] resize(int[][] array2D) {
// To be implemented in part (b)
return null;
}
}
public class ArrayResizerTester {
public static void main(String[] args) {
int[][] arr = {
{2, 1, 0},
{1, 3, 2},
{0, 0, 0},
{4, 5, 6}
};
System.out.println("isNonZeroRow(arr, 0): " + ArrayResizer.isNonZeroRow(arr, 0)); // false
System.out.println("isNonZeroRow(arr, 1): " + ArrayResizer.isNonZeroRow(arr, 1)); // true
System.out.println("isNonZeroRow(arr, 2): " + ArrayResizer.isNonZeroRow(arr, 2)); // false
System.out.println("isNonZeroRow(arr, 3): " + ArrayResizer.isNonZeroRow(arr, 3)); // true
int[][] smaller = ArrayResizer.resize(arr);
System.out.println("Resized array:");
if (smaller != null) {
for (int[] row : smaller) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
} else {
System.out.println("Returned null.");
}
}
}
import java.util.*;
public class Week16 {
public static void main(String[] args) {
String myName = ""; // add your name
System.out.println("Week 16" + " - " + myName);
// Menu
System.out.println("Menu");
System.out.println("E1 - Example 1");
System.out.println("Q - Quit");
// setup Scanner
Scanner in = new Scanner(System.in);
System.out.print("Choice: ");
String choice = in.nextLine();
// switch choices
switch (choice) {
case "E1":
System.out.println("Example 1");
example1();
break;
case "E2":
System.out.println("Example 2");
example2();
break;
case "E3":
System.out.println("Example 3");
example3();
break;
case "E4":
System.out.println("Example 4");
example4();
break;
case "E5":
System.out.println("Example 5");
example5();
break;
case "Q":
System.out.println("Quitting..!");
break;
}
}
// example1 method
public static void example1() {
// create an array of friends
// for loop
// enhanced for loop
}
// example2 method
public static void example2() {
// create an array of horses
// enhanced for loop
}
// example3 method
public static void example3() {
// create array
int[] values = { 6, 2, 1, 7, 12, 5 };
// assign first value
int first = values[0];
// loop
// if it's not the last element, copy the next one over
// last element gets first
// print
}
// example4 method
public static void example4() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = in.nextInt();
int[] values = new int[n];
System.out.print("Enter the elements:");
for (int i = 0; i < n; i++) {
values[i] = in.nextInt();
}
// Checking for adjacent duplicates
}
// example5 method
public static void example5() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = in.nextInt();
int[] values = new int[n];
System.out.print("Enter the elements:");
for (int i = 0; i < n; i++) {
values[i] = in.nextInt();
}
// Checking for any duplicates in the array
}
// Method to check for adjacent duplicates
public static boolean hasAdjacentDuplicates(int[] values) {
for (int i = 0; i < values.length - 1; i++) {
if (values[i] == values[i + 1]) {
return true;
}
}
return false;
}
// Method to check for duplicates anywhere in the array
public static boolean hasAnyDuplicates(int[] values) {
for (int i = 0; i < values.length; i++) {
for (int j = i + 1; j < values.length; j++) {
if (values[i] == values[j]) {
return true;
}
}
}
return false;
}
// printArray method
public static void printArray(int[] arr) {
System.out.println("Print Array");
System.out.println("Index\tValue");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + "\t" + arr[i]);
}
}
}
public class CommandLineArgs {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}public class CommandLineSum {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers.");
return;
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}import java.util.*;
public class W16Problem1
{
public static void main(String[] args)
{
System.out.println("Problem 1");
// Array to store 1000 random numbers
// Array to track occurrences of numbers 1-100
// Fill the first array with random numbers from 1 to 10
// Count the occurrences using an enhanced for loop
// Adjust index since 1 should go to index 0
// Print frequency of each number
}
}import java.util.*;
public class W16Problem2
{
public static void main(String[] args)
{
System.out.println("Problem 2");
// Array to hold 10000 random numbers
// Array to store frequency counts (index 0 for 0, index 99 for 99)
// Fill the first array with random numbers from 0 to 99
// Sort the array in ascending order
// Count occurrences of each number using an enhanced for loop
// by incrementing the corresponding index in frequency array
// Find most and least frequent numbers
// Create variables to track the most and least frequent numbers
// Print the frequency of each number in the range 0-99
// Print the most and least frequent numbers
}
}public class W16Problem3 {
public static boolean hasConsecutiveIncreasing(int[] values) {
// TODO: Implement logic to check for consecutive increasing numbers
return false;
}
public static void main(String[] args) {
// Test 1
int[] values1 = {1, 2, 3, 5, 7};
// Expected output: true
System.out.println(hasConsecutiveIncreasing(values1));
// Test 2
int[] values2 = {1, 1, 1, 1, 1};
// Expected output: false
System.out.println(hasConsecutiveIncreasing(values2));
}
}
public class W16Problem4 {
public static boolean hasPairWithSum(int[] values, int targetSum) {
// TODO: Implement logic to check if any two elements sum to targetSum
return false;
}
public static void main(String[] args) {
// Test 1
int[] values1 = {4, 7, 1, 2, 8};
int targetSum1 = 9;
// Expected output: true
System.out.println(hasPairWithSum(values1, targetSum1));
// Test 2
int[] values2 = {1, 7, 1, 3, 10};
int targetSum2 = 9;
// Expected output: false
System.out.println(hasPairWithSum(values2, targetSum2));
}
}
public class W16Problem5 {
public static int countUniqueElements(int[] values) {
// TODO: Implement logic to count unique elements
return 0;
}
public static void main(String[] args) {
// Test 1
int[] values1 = {1, 2, 3, 2, 4, 1, 5};
// Expected output: 5
System.out.println(countUniqueElements(values1));
// Test 2
int[] values2 = {1, 2, 1, 2, 1, 2, 1};
// Expected output: 2
System.out.println(countUniqueElements(values2));
}
}public class W16Problem6 {
public static void main(String[] args) {
// Create an array of size 10000
// Fill array with random numbers from 0 to 99
// Sort the array to group identical numbers together
// Variables to track current count and mode
// Variables to track minimum frequency
// Count consecutive occurrences
// Same number continues
// Check if previous run is the mode
// Check if previous run is the minimum (excluding the current run)
// Reset count for new number
// Print results
}
}public class Horse {
private String name;
private int weight;
public Horse(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
}/**
* HorseBarn - A class to manage horses in a barn with numbered spaces.
* Each space can hold at most one horse, and each horse has a unique name.
*/
public class HorseBarn {
// Instance Variables
private Horse[] spaces; // Array to store horses, null represents empty space
/**
* Constructor for HorseBarn
*
* @param numberOfSpaces the number of spaces in the barn
*/
public HorseBarn(int numberOfSpaces) {
spaces = new Horse[numberOfSpaces];
}
/**
* Returns the index of the space that contains the horse with the specified
* name.
*
* @param name the name of the horse to find
* @return the index of the space containing the horse with the specified name;
* -1 if no horse with the specified name is in the barn.
*/
public int findHorseSpace(String name) {
// Input validation
if (name == null) {
return -1;
}
// Search through all spaces
for (int i = 0; i < spaces.length; i++) {
// Check if space has a horse and if the names match
if (spaces[i] != null && spaces[i].getName().equals(name)) {
return i;
}
}
// Horse not found
return -1;
}
/**
* Consolidates the barn by moving horses so that the horses are in adjacent
* spaces,
* starting at index 0, with no empty space between any two horses.
* The order of the horses remains the same as before the consolidation.
*/
public void consolidate() {
// Create temporary array
Horse[] temp = new Horse[spaces.length];
int nextPosition = 0;
// Copy non-null horses in order
for (int i = 0; i < spaces.length; i++) {
if (spaces[i] != null) {
temp[nextPosition] = spaces[i];
nextPosition++;
}
}
// Replace original array with consolidated version
spaces = temp;
}
/**
* Adds a horse to the first available (empty) space in the barn.
*
* @param horse the horse to add
* @return true if the horse was added successfully, false if the barn is full
* or if a horse with the same name already exists
*/
public boolean addHorse(Horse horse) {
// Input validation
if (horse == null) {
return false;
}
// Check if horse with same name already exists
if (findHorseSpace(horse.getName()) != -1) {
return false;
}
// Find first empty space
for (int i = 0; i < spaces.length; i++) {
if (spaces[i] == null) {
spaces[i] = horse;
return true;
}
}
// No empty space found
return false;
}
/**
* Removes a horse from the barn by name.
*
* @param name the name of the horse to remove
* @return true if the horse was removed successfully, false if the horse wasn't
* found
*/
public boolean removeHorse(String name) {
int index = findHorseSpace(name);
if (index != -1) {
spaces[index] = null;
return true;
}
return false;
}
/**
* Returns the horse at the specified index.
*
* @param index the index of the space to check
* @return the horse at the specified space, or null if the space is empty
* or the index is invalid
*/
public Horse getHorse(int index) {
if (index >= 0 && index < spaces.length) {
return spaces[index];
}
return null;
}
/**
* Returns the number of spaces in the barn.
*
* @return the total number of spaces
*/
public int getSpaces() {
return spaces.length;
}
/**
* Returns the number of horses currently in the barn.
*
* @return the number of occupied spaces
*/
public int getNumberOfHorses() {
int count = 0;
for (Horse horse : spaces) {
if (horse != null) {
count++;
}
}
return count;
}
/**
* Returns true if the barn is empty (contains no horses).
*
* @return true if the barn is empty, false otherwise
*/
public boolean isEmpty() {
return getNumberOfHorses() == 0;
}
/**
* Returns true if the barn is full (all spaces occupied).
*
* @return true if the barn is full, false otherwise
*/
public boolean isFull() {
return getNumberOfHorses() == spaces.length;
}
/**
* Returns a string representation of the barn.
*
* @return a string showing the contents of each space in the barn
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("HorseBarn with ").append(spaces.length).append(" spaces:\n");
for (int i = 0; i < spaces.length; i++) {
result.append("Space ").append(i).append(": ");
if (spaces[i] == null) {
result.append("empty");
} else {
result.append(spaces[i].getName()).append(" (").append(spaces[i].getWeight()).append(" lbs)");
}
result.append("\n");
}
return result.toString();
}
public static void main(String[] args) {
// Create test barn
// Test 1: Empty barn
// Add horses
// print the barn layout
// Test 2: Find existing horses
// Test 3: Find non-existent horse
// Test 4: Consolidate
}
}
public class Vehicle {
private String licensePlate;
private String make;
private String model;
public Vehicle(String licensePlate, String make, String model) {
this.licensePlate = licensePlate;
this.make = make;
this.model = model;
}
public String getLicensePlate() { return licensePlate; }
public String getMake() { return make; }
public String getModel() { return model; }
@Override
public String toString() {
return make + " " + model + " (" + licensePlate + ")";
}
}public class ParkingGarage {
private Vehicle[] spots;
private static final double HOURLY_RATE = 5.00; // $5 per hour
public ParkingGarage(int numSpots) {
spots = new Vehicle[numSpots];
}
/**
* Parks a vehicle in the first available appropriate spot
* @param vehicle the vehicle to park
* @return the spot number if successful, -1 if no spots available
*/
public int parkVehicle(Vehicle vehicle) {
// TODO: Implement this method
return -1;
}
/**
* Removes a vehicle from the garage and calculates parking fee
* @param licensePlate the license plate of the vehicle to remove
* @return the parking fee in dollars, -1 if vehicle not found
*/
public double removeVehicle(String licensePlate) {
// TODO: Implement this method
return -1.0;
}
/**
* Finds a vehicle by license plate
* @param licensePlate the license plate to search for
* @return the spot number if found, -1 if not found
*/
public int findVehicle(String licensePlate) {
// TODO: Implement this method
return -1;
}
/**
* Returns a formatted string representing the parking garage layout.
* Shows which spots are occupied and by which vehicle.
*
* @return A string representation of the parking garage.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Parking Garage Status:\n");
for (int i = 0; i < spots.length; i++) {
sb.append("Spot ").append(i).append(": ");
if (spots[i] != null) {
sb.append(spots[i]); // Calls Vehicle's toString()
} else {
sb.append("Empty");
}
sb.append("\n");
}
return sb.toString();
}
/**
* The main method for testing the Parking Garage Management System.
*/
public static void main(String[] args) {
System.out.println("Welcome to the Parking Garage!");
// Create a parking garage with 10 spots
// Create some vehicles
Vehicle car1 = new Vehicle("ABC123", "Dodge", "Charger");
Vehicle car2 = new Vehicle("XYZ789", "Honda", "Civic");
Vehicle car3 = new Vehicle("LMN456", "Ford", "Escape");
Vehicle car4 = new Vehicle("NULL", "Toyota", "Corolla");
Vehicle car5 = new Vehicle("VROOM", "Dodge", "Challenger");
// Park vehicles
// Find vehicle (ask the user for a Vehicle to find)
// Remove a vehicle and calculate fee
}
}