Practical 2: Basic Usage of Java with
1. Overview
This Java program allows the user to perform various operations such as inputting primitive data types, checking if a number is an Armstrong number, calculating the sum of digits of a number, converting between Fahrenheit and Celsius, and computing the circumference and area of a circle.
2. Imports
The only package imported is the java.util.Scanner
. It is a Java utility that provides methods to read input of primitive types from the console. This program uses it to collect user inputs.
2.1 Understanding the Imports
In Java, 'import' allows us to use external classes, functions, and packages in our program without needing to reference them with their fully qualified names. Let's delve into the specific imports used in this code:
2.1.1 java.util.Scanner
The java.util.Scanner
class provides a simple and efficient way to get input from the user. It can read input of various types, such as integers, floats, doubles, and strings, from various sources like the keyboard (System.in), files, and other input streams.
Commonly used methods include nextInt()
, nextFloat()
, and next()
.
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
This snippet initializes a Scanner object to read from the standard input and then reads an integer input from the user.
2.2 Dissecting the Class Structure
Understanding the class structure is crucial, as it forms the blueprint of our program. The entire program is encapsulated within a single class named p2
. The class contains a private static scanner object, a main
method, and multiple private static methods.
2.2.1 Public Class
The code is encapsulated within a public class
named p2
. Being public means this class can be accessed from other classes. In Java, the filename should match the public class name, which means our file should be named p2.java
.
2.2.2 Private Static Scanner
Inside the class, we declare a private static Scanner
object. The keyword private
ensures that this Scanner object can only be accessed within this class, and static
means that it belongs to the class rather than a particular instance of the class.
2.2.3 Main Method
The main
method acts as the entry point to the program. When we run the program, the code within this method gets executed. Inside the main
method, we present users with a loop offering various functionalities like inputting primitive data, checking for an Armstrong number, and more.
2.2.4 Helper Methods
Beyond the main
method, the class contains several helper methods like inputPrimitiveData()
, checkArmstrong()
, and others. These methods are tasked with specific functions, allowing the main method to remain concise and enhancing the readability and modularity of the code. They are defined as private static
, meaning they can only be accessed within the class and don't require an instance of the class to be called.
2.3 Main Method
The main
method is the entry point for the Java program. In this method:
- The user is presented with a loop, where they can choose from a list of operations.
- Based on the user's input, a specific operation is executed.
- The loop continues until the user decides to exit the program.
2.4 Inputting Primitive Data
This function prompts the user to input values for four primitive data types: int
, float
, double
, and char
. The entered values are then printed back to the console.
2.5 Checking Armstrong Number
An Armstrong number (also known as narcissistic number) of a given number of digits is an integer such that the sum of its own digits each raised to the power of the number of digits equals the number itself. For instance, 153 is an Armstrong number because \(1^3 + 5^3 + 3^3 = 153\).
This function checks and informs whether the given number is an Armstrong number or not.
2.6 Calculating Sum of Digits
This function takes a number as input (between 0 and 1000) and calculates the sum of its digits. For example, if the input is 153, the output will be \(1 + 5 + 3 = 9\).
2.7 Temperature Conversion
The program provides two functions for temperature conversion:
- Converting Fahrenheit to Celsius using the formula \(Celsius = \frac{(Fahrenheit - 32) \times 5}{9}\).
- Converting Celsius to Fahrenheit using the formula \(Fahrenheit = Celsius \times \frac{9}{5} + 32\).
2.8 Calculating Circle Metrics
This function takes the radius of a circle as input and calculates:
- The circumference using the formula \(2 \times \pi \times radius\).
- The area using the formula \(\pi \times radius^2\).
3. Code
Now that we've explored the functionality of the program, let's look at its code below:
package practicals.p2;
import java.util.Scanner;
public class p2 {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("\nChoose an operation:");
System.out.println("1. Input Primitive Data");
System.out.println("2. Check Armstrong Number");
System.out.println("3. Calculate Sum of Digits");
System.out.println("4. Convert Fahrenheit to Celsius");
System.out.println("5. Convert Celsius to Fahrenheit");
System.out.println("6. Calculate Circumference and Area of Circle");
System.out.println("7. Exit");
System.out.print("Enter your choice: ");
switch (scanner.nextInt()) {
case 1: inputPrimitiveData(); break;
case 2: checkArmstrong(); break;
case 3: sumOfDigits(); break;
case 4: convertFahrenheitToCelsius(); break;
case 5: convertCelsiusToFahrenheit(); break;
case 6: calculateCircleMetrics(); break;
case 7: System.out.println("Exiting... Thank you!"); return;
default: System.out.println("Invalid choice!"); break;
}
}
}
private static void inputPrimitiveData() {
System.out.println("Enter int, float, double, and char values:");
int i = scanner.nextInt();
float f = scanner.nextFloat();
double d = scanner.nextDouble();
char c = scanner.next().charAt(0);
System.out.printf("You entered: %d, %f, %f, %c%n", i, f, d, c);
}
private static void checkArmstrong() {
System.out.print("Enter a number: ");
int num = scanner.nextInt(), temp = num, sum = 0, digits = (int)Math.log10(num) + 1;
while (temp != 0) {
sum += Math.pow(temp % 10, digits);
temp /= 10;
}
System.out.println(num + " has " + digits + " digits and" + (sum == num ? " is" : " is not") + " an Armstrong number.");
}
private static void sumOfDigits() {
System.out.print("Enter a number (0-1000): ");
int num = scanner.nextInt(), sum = 0;
if (num < 0 || num > 1000) { System.out.println("Error! Number out of range."); return; }
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of digits: " + sum);
}
private static void convertFahrenheitToCelsius() {
System.out.print("Enter temperature in Fahrenheit: ");
double fahrenheit = scanner.nextDouble();
double celsius = (fahrenheit - 32) * 5/9;
System.out.println(fahrenheit + "°F = " + celsius + "°C");
}
private static void convertCelsiusToFahrenheit() {
System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();
double fahrenheit = (celsius * 9/5 + 32);
System.out.println(celsius + "°C = " + fahrenheit + "°F");
}
private static void calculateCircleMetrics() {
System.out.print("Enter radius: ");
double r = scanner.nextDouble();
System.out.println("Circumference: " + 2 * Math.PI * r);
System.out.println("Area: " + Math.PI * r * r);
}
}
4. Sample Output
Upon executing the program, users will be presented with a menu of choices. Here's a brief demonstration of how the interaction might appear:
Choose an operation:
1. Input Primitive Data
2. Check Armstrong Number
3. Calculate Sum of Digits
4. Convert Fahrenheit to Celsius
5. Convert Celsius to Fahrenheit
6. Calculate Circumference and Area of Circle
7. Exit
Enter your choice: 1
Enter int, float, double, and char values: 10 2.5 3.14 A
You entered: 10, 2.500000, 3.140000, A
The above is just a single demonstration of the "Input Primitive Data" operation. You can explore other functionalities in a similar interactive manner.
5. Additional Resources and References
For those eager to dive deeper into Java and explore beyond the basics, here are some recommended resources:
Books:
- Java: The Complete Reference by Herbert Schildt
- Effective Java by Joshua Bloch
- Java Concurrency in Practice by Brian Goetz