Expressions and Output
- Popcorn Hack 1
- Popcorn Hack 2
- Homework Hack 1
- Homework Hack 2 - Calculator MenuI’ve created a complete Calculator Menu program that:
Popcorn Hack 1
Key Formatting Tools (from memory):
\n- Newline character, moves cursor to the next line\t- Tab character, adds horizontal spacing/indentationSystem.out.print()- Prints without adding a newline at the endSystem.out.println()- Prints with a newline at the endSystem.out.printf()- Formatted print, allows placeholders like%d,%s,%f\\- Escape sequence for backslash
Example line using multiple tools: System.out.println(“Name: John\nGPA: 3.85\nQuote: "Hello\World"”);
Popcorn Hack 2
System.out.println()- Prints text and automatically adds a newline at the end- Used for the menu title, menu options, and informational messages
- Makes each item appear on its own line for better readability
System.out.print()- Prints text WITHOUT a newline at the end- Used for
"Choose an option: "so the user’s input appears on the same line - Creates a cleaner prompt experience
- Used for
- String concatenation (
+) - Combines strings and variables- Used in
"You selected option: " + choice - Used in
"There are " + optionCount + " total options." - Allows dynamic output that includes user input and variable values
- Used in
- Consistent formatting structure - The
====borders and numbered list format- Creates visual hierarchy and organization
- Makes the menu easy to scan and understand
How they make the output cleaner/better:
println()for menu items creates vertical spacing and clear separation between options, making the menu easy to read at a glanceprint()for the prompt keeps the input on the same line as the question, creating a natural user experience (like:Choose an option: 1instead of having the input on a new line)- String concatenation provides personalized feedback by incorporating the user’s choice into the response
- Numbered list format (1, 2, 3) gives users a clear way to reference their choice
- Border decoration (
====) visually separates the menu from other output, drawing attention to the interactive section
Homework Hack 1
1. Predict Output:
AP CSA
Rocks!
2. Fix the Bug:
System.out.println("C:\\Users\\Student");
Explanation: The backslash \ is an escape character, so we need \\ to print a literal backslash.
3. Menu Hack:
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("==== Main Menu ====");
System.out.println("1. Start Game");
System.out.println("2. Instructions");
System.out.println("3. Exit");
System.out.println("4. Credits"); // Added 4th print line (Homework Point here)
System.out.print("Choose an option: ");
int choice = sc.nextInt();
System.out.println("You selected option: " + choice);
int optionCount = 4;
System.out.println("There are " + optionCount + " total options.");
}
}
Menu.main(null);
Failed to start the Kernel.
Unknown option: '-R-ea'
Usage: jbang run -o [-hin] [--[no-]cds] [--ea] [--esa] --fresh [--insecure]
[--jsh] --quiet --verbose [-c[=<literalScript>]] [-d
[=<debugString>]] [--jfr[=<flightRecorderString>]]
[--catalog=<catalog>] [--config=<config>] [-j=<javaVersion>]
[-m=<main>] [--source-type=<forceType>] [--cp=<classpaths>]...
[-D=<String=String>]... [--deps=<dependencies>]...
[--files=<resources>]...
[--java-options=<javaRuntimeOptions>]...
[--javaagent=<String=String>]... [--repos=<repositories>]...
[-s=<sources>]... [<scriptOrFile>] [<userParams>...]
Builds and runs provided script.
[<scriptOrFile>] A reference to a source file
[<userParams>...] Parameters to pass on to the script
-c, --code[=<literalScript>]
Run the given string as code
--catalog=<catalog> Path to catalog file to be used instead of the
default
--[no-]cds If specified Class Data Sharing (CDS) will be used
for building and running (requires Java 13+)
--config=<config> Path to config file to be used instead of the
default
--cp, --class-path=<classpaths>
Add class path entries.
-d, --debug[=<debugString>]
Launch with java debug enabled on specified port
(default: 4004)
-D=<String=String> set a system property
--deps=<dependencies> Add additional dependencies (Use commas to
separate them).
--ea, --enableassertions
Enable assertions
--esa, --enablesystemassertions
Enable system assertions
--files=<resources> Add additional files.
--fresh Make sure we use fresh (i.e. non-cached) resources.
-h, --help Display help/info. Use 'jbang <command> -h' for
detailed usage.
-i, --interactive Activate interactive mode
--insecure Enable insecure trust of all SSL certificates.
-j, --java=<javaVersion> JDK version to use for running the script.
--java-options=<javaRuntimeOptions>
A Java runtime option
--javaagent=<String=String>
--jfr[=<flightRecorderString>]
Launch with Java Flight Recorder enabled.
--jsh Force input to be interpreted with jsh/jshell.
Deprecated: use '--source-type jshell'
-m, --main=<main> Main class to use when running. Used primarily for
running jar's.
-n, --native Build using native-image
-o, --offline Work offline. Fail-fast if dependencies are
missing. No connections will be attempted
--quiet jbang will be quiet, only print when error occurs.
--repos=<repositories> Add additional repositories.
-s, --sources=<sources> Add additional sources.
--source-type=<forceType>
Force input to be interpreted as the given type.
Can be: java, jshell, groovy, kotlin, or markdown
--verbose jbang will be verbose on what it does.
View Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details.
4. Challenge:
System.out.printf("Pi = %.2f\n", Math.PI);
Pi = 3.14
java.io.PrintStream@4c970aa1
Homework Hack 2 - Calculator MenuI’ve created a complete Calculator Menu program that:
Features:
- Displays a formatted menu with 4 operations
- Takes user input for menu choice
- Prompts for two numbers
- Uses arithmetic expressions (
+,-,*,/) to compute results - Handles division by zero error
- Uses
printfto format the result with 2 decimal places - Includes a
switchstatement for clean operation selection
Example Output:
==== Calculator Menu ====
1. Add
2. Subtract
3. Multiply
4. Divide
Choose an option: 1
Enter first number: 10
Enter second number: 5
Result: 15.00
import java.util.Scanner;
public class CalculatorMenu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Print menu
System.out.println("==== Calculator Menu ====");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
// Get user choice
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
// Get two numbers
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
// Calculate and display result
double result = 0;
boolean validOperation = true;
switch(choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
if(num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Cannot divide by zero!");
validOperation = false;
}
break;
default:
System.out.println("Invalid option!");
validOperation = false;
}
if(validOperation) {
System.out.printf("Result: %.2f\n", result);
}
scanner.close();
}
}
CalculatorMenu.main(null);
Failed to start the Kernel.
Unknown option: '-R-ea'
Usage: jbang run -o [-hin] [--[no-]cds] [--ea] [--esa] --fresh [--insecure]
[--jsh] --quiet --verbose [-c[=<literalScript>]] [-d
[=<debugString>]] [--jfr[=<flightRecorderString>]]
[--catalog=<catalog>] [--config=<config>] [-j=<javaVersion>]
[-m=<main>] [--source-type=<forceType>] [--cp=<classpaths>]...
[-D=<String=String>]... [--deps=<dependencies>]...
[--files=<resources>]...
[--java-options=<javaRuntimeOptions>]...
[--javaagent=<String=String>]... [--repos=<repositories>]...
[-s=<sources>]... [<scriptOrFile>] [<userParams>...]
Builds and runs provided script.
[<scriptOrFile>] A reference to a source file
[<userParams>...] Parameters to pass on to the script
-c, --code[=<literalScript>]
Run the given string as code
--catalog=<catalog> Path to catalog file to be used instead of the
default
--[no-]cds If specified Class Data Sharing (CDS) will be used
for building and running (requires Java 13+)
--config=<config> Path to config file to be used instead of the
default
--cp, --class-path=<classpaths>
Add class path entries.
-d, --debug[=<debugString>]
Launch with java debug enabled on specified port
(default: 4004)
-D=<String=String> set a system property
--deps=<dependencies> Add additional dependencies (Use commas to
separate them).
--ea, --enableassertions
Enable assertions
--esa, --enablesystemassertions
Enable system assertions
--files=<resources> Add additional files.
--fresh Make sure we use fresh (i.e. non-cached) resources.
-h, --help Display help/info. Use 'jbang <command> -h' for
detailed usage.
-i, --interactive Activate interactive mode
--insecure Enable insecure trust of all SSL certificates.
-j, --java=<javaVersion> JDK version to use for running the script.
--java-options=<javaRuntimeOptions>
A Java runtime option
--javaagent=<String=String>
--jfr[=<flightRecorderString>]
Launch with Java Flight Recorder enabled.
--jsh Force input to be interpreted with jsh/jshell.
Deprecated: use '--source-type jshell'
-m, --main=<main> Main class to use when running. Used primarily for
running jar's.
-n, --native Build using native-image
-o, --offline Work offline. Fail-fast if dependencies are
missing. No connections will be attempted
--quiet jbang will be quiet, only print when error occurs.
--repos=<repositories> Add additional repositories.
-s, --sources=<sources> Add additional sources.
--source-type=<forceType>
Force input to be interpreted as the given type.
Can be: java, jshell, groovy, kotlin, or markdown
--verbose jbang will be verbose on what it does.
View Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details.