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 [Link];
public class AverageAndCount {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of elements: ");
int n = [Link]();
double[] numbers = new double[n];
[Link]("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = [Link]();
}
double sum = 0;
for (double number : numbers) {
sum += number;
}
double average = sum / n;
int countGreaterThanAverage = 0;
for (double number : numbers) {
if (number > average) {
countGreaterThanAverage++;
}
}
[Link]("Average: %.2f%n", average);
[Link]("Count of numbers greater than the average: " +
countGreaterThanAverage);
[Link]();
}
}
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 [Link];
public class PasswordValidator {
public static boolean isValidPassword(String password) {
// Check if the password length is at least 8 characters
if ([Link]() < 8) {
return false;
}
// Check for only letters and digits, and count digits
int digitCount = 0;
for (char c : [Link]()) {
if ( && ) {
return false; // Invalid character found
}
if ([Link](c)) {
digitCount++;
}
}
// Check if there are at least two digits
return digitCount >= 2;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for a password
[Link]("Enter a password: ");
String password = [Link]();
// Validate the password
if (isValidPassword(password)) {
[Link]("Valid Password");
} else {
[Link]("Invalid Password");
}
// Close the scanner
[Link]();
}
}