Introduction
In this lesson, we will focus on Implementing Core Features of console-based applications in Java. Building on the foundational concepts you've learned, we will explore how to handle user input, control the flow of your application with conditional statements, perform repetitive tasks using loops, and manage exceptions effectively. By the end of this lesson, you'll have the skills to create robust and interactive console applications.
Handling User Input with the Scanner Class
User input is essential in many applications. In Java, we handle user input through the Scanner class, which allows us to read various data types from the console. To use the Scanner class, we first need to import it:
import java.util.Scanner;
Here's a simple program that captures user input:
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
// Create a Scanner object
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
// Read user input
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
// Close the scanner to avoid resource leaks
scanner.close();
}
}
Output:
Enter your name:
John
Hello, John!
Control Application Flow with Conditional Statements
Conditional statements if and switch play a vital role in determining how our applications respond to user input. Using these statements allows us to execute different blocks of code based on specific conditions. Below is an example using an if statement:
import java.util.Scanner;
public class AgeVerification {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
scanner.close();
}
}
Output:
Enter your age:
20
You are an adult.
Using Loops for Repetitive Tasks
Loops are necessary when performing repetitive tasks. Java provides three different types of loops: for, while, and do-while. Let’s consider an example where we print the first ten natural numbers using a for loop:
public class PrintNaturalNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Effective Exception Handling Techniques
To create resilient applications, it's important to handle errors and exceptions properly. We can use try-catch blocks to manage exceptions, ensuring that our application doesn’t crash unexpectedly. Here’s an example of handling an arithmetic exception:
import java.util.Scanner;
public class DivisionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter dividend: ");
int dividend = scanner.nextInt();
System.out.print("Enter divisor: ");
int divisor = scanner.nextInt();
try {
int result = dividend / divisor;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} finally {
scanner.close();
}
}
}
Output:
Enter dividend:
10
Enter divisor:
0
Error: Cannot divide by zero.
Summary / Key Takeaways
In this lesson on Implementing Core Features, you have learned:
- User Input Handling: Utilize the Scanner class to gather input from users effectively.
- Control Flow: Employ conditional statements (
if,switch) to dictate application behavior based on user input. - Loops: Use
for,while, anddo-whileloops for executing repetitive tasks in your applications. - Error Handling: Implement
try-catchblocks to handle exceptions gracefully, maintaining application stability. - Resource Management: Always close the Scanner and other resources after use to prevent memory leaks.