Basic Calculator: Implement a program using different Data Types and Scanner class for user
input/output.
import [Link];
public class BasicCalculator {
public static void main(String[] args) {
// Creating Scanner object for user input
Scanner input = new Scanner([Link]);
[Link]("--- Welcome to the Java Calculator ---");
// 1. Demonstration of Data Types (double for precision)
[Link]("Enter first number: ");
double num1 = [Link]();
[Link]("Enter second number: ");
double num2 = [Link]();
// 2. Using char data type for the operator
[Link]("Choose an operator (+, -, *, /): ");
char operator = [Link]().charAt(0);
double result = 0;
boolean validOperation = true;
// 3. Logic using Switch-Case (Core Programming Logic)
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
// [Link] Division by Zero
if (num2 != 0) {
result = num1 / num2;
} else {
[Link]("Error: Division by zero is undefined.");
validOperation = false;
}
break;
default:
[Link]("Error: Invalid operator entered.");
validOperation = false;
}
// 5. Formatted Output
if (validOperation) {
[Link]("Calculation Result: %.2f %c %.2f = %.2f\n", num1, operator, num2,
result);
} [Link]();
}}
Program on datatypes and Scanner class
"Profile Generator," collecting different types of data to show how Scanner methods
change based on the variable type.
import [Link];
public class DataTypeDemo {
public static void main(String[] args) {
// Initialize Scanner for console input
Scanner sc = new Scanner([Link]);
[Link]("--- Student Profile Registration ---");
// 1. String (Non-primitive) - Using nextLine()
[Link]("Enter your full name: ");
String name = [Link]();
// 2. Integer (Primitive) - Using nextInt()
[Link]("Enter your age: ");
int age = [Link]();
// 3. Character (Primitive) - Extracted from a String
[Link]("Enter your Gender (M/F/O): ");
char gender = [Link]().charAt(0);
// 4. Double (Primitive) - Using nextDouble() for precision
[Link]("Enter your current CGPA: ");
double cgpa = [Link]();
// 5. Long (Primitive) - For large numeric values
[Link]("Enter your 10-digit Mobile Number: ");
long mobile = [Link]();
// 6. Boolean (Primitive) - Using nextBoolean()
[Link]("Are you a hosteller? (true/false): ");
boolean isHosteller = [Link]();
// Displaying the gathered information using escape sequences
[Link]("\n--- Registration Summary ---");
[Link]("Name\t\t: " + name);
[Link]("Age\t\t: " + age + " years");
[Link]("Gender\t\t: " + gender);
[Link]("CGPA\t\t: " + cgpa);
[Link]("Contact\t\t: +91-" + mobile);
[Link]("Hostel Facility\t: " + (isHosteller ? "Yes" : "No"));
[Link]();
}
}