1. Write a Java program using arrays to solve the problem.
The problem is to read n
numbers, get the average of these numbers, and find the number of the items greated
than the average.
import java.util.Scanner;
public class AverageAndCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
double[] numbers = new double[n];
System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextDouble();
}
double sum = 0;
for (double number : numbers) {
sum += number;
}
double average = sum / n;
int countGreaterThanAverage = 0;
for (double number : numbers) {
if (number > average) {
countGreaterThanAverage++;
}
}
System.out.printf("Average: %.2f%n", average);
System.out.println("Count of numbers greater than the average: " +
countGreaterThanAverage);
scanner.close();
}
}
2. Some Websites impose certain rules for passwords. Write a method that checks
whether a string is a valid password. Suppose the password rule is follows:
*A password must have at least eight characters
*A password consists of only letters and digits.
*A password must contain at least two digits.
Write a Java program that prompts the user to enter a password and displays "Valid
Password" if the rule is followed or "Valid Password" if the rule is followed or
"Invalid Password" otherwise.
import java.util.Scanner;
public class PasswordValidator {
public static boolean isValidPassword(String password) {
// Check if the password length is at least 8 characters
if (password.length() < 8) {
return false;
}
// Check for only letters and digits, and count digits
int digitCount = 0;
for (char c : password.toCharArray()) {
if (!Character.isLetter(c) && !Character.isDigit(c)) {
return false; // Invalid character found
}
if (Character.isDigit(c)) {
digitCount++;
}
}
// Check if there are at least two digits
return digitCount >= 2;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for a password
System.out.print("Enter a password: ");
String password = scanner.nextLine();
// Validate the password
if (isValidPassword(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
// Close the scanner
scanner.close();
}
}