Java Lab
Java Lab
try {
int num = Integer.parseInt(args[0]);
if (num < 0) {
System.out.println("Factorial is not defined for negative numbers.");
return;
}
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("The factorial of " + num + " is: " + factorial);
} catch (NumberFormatException e) {
System.out.println("Please provide a valid integer.");
}
}
}
----------------------
public class PalindromeCheck {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please provide a string to check.");
return;
}
if (input.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
-------------
public class SumArgs {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers as arguments.");
return;
}
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
} catch (NumberFormatException e) {
System.out.println("Please provide valid integers.");
}
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create objects (instances of the class)
Car car1 = new Car("Toyota", "Corolla", 2020);
Car car2 = new Car("Honda", "Civic", 2021);
// Parent Class
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
// Child Class
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks: Woof! Woof!");
}
}
// Main Class
public class SmallInheritanceExample {
public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // Calls the parent class method
package mypackage;
javac mypackage/MyClass.java
import mypackage.MyClass;
// Create a JLabel
JLabel label = new JLabel("Click the button!");
label.setBounds(100, 50, 150, 30);
frame.add(label);
// Create a JButton
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 100, 30);
frame.add(button);