Share
Explore

Java Practice Questions: Level Basic

Topics covered:
Simple Object Formulation
Arrays

Question:
In this problem, you are provided with an application code base that models a street driving scenario. The application includes several classes: Car, TrafficLight, and Street.
The Car class has an instance variable waitTime that represents the time (in seconds) that the car has been waiting at the traffic light.
The TrafficLight class simulates a traffic light that can be either red or green. It has a color instance variable that represents the current color of the light and a switchLight method to change the color of the light.
The Street class contains an array of Car objects representing all cars on the street at a given moment.
Your task is to implement a calculateAverageWaitTime method in the Street class. This method should return the average time that cars spend waiting at the red light. The average should be calculated from the waitTime of all the cars on the street.
Here's the provided code:
public class Car {
private int waitTime;

public Car(int waitTime) {
this.waitTime = waitTime;
}

public int getWaitTime() {
return waitTime;
}
}

public class TrafficLight {
private String color;

public TrafficLight(String color) {
this.color = color;
}

public void switchLight() {
color = color.equals("red") ? "green" : "red";
}

public String getColor() {
return color;
}
}

public class Street {
private Car[] cars;
private TrafficLight trafficLight;

public Street(Car[] cars, TrafficLight trafficLight) {
this.cars = cars;
this.trafficLight = trafficLight;
}

// Your task is to implement this method
public double calculateAverageWaitTime() {
// Your code here
}
}

Write a Method to create 10 cars and run the simulation.

Implement the calculateAverageWaitTime method in the space provided below.
Answer:
public double calculateAverageWaitTime() {
int totalWaitTime = 0;
for (Car car : cars) {
totalWaitTime += car.getWaitTime();
}
return (double) totalWaitTime / cars.length;
}


Question:
Your task is to implement a Java application that simulates a basic text-based game called "Guess the Number". The program should choose a random number between 1 and 100 (inclusive) and then ask the user to guess this number.
Here are the rules:
If the guess is correct, print a congratulatory message and end the game.
If the guess is less than the target number, print "Too low! Try again." and allow the user to guess again.
If the guess is greater than the target number, print "Too high! Try again." and allow the user to guess again.
The user should be allowed to make up to 10 attempts to guess the number. If they do not guess the number in 10 attempts, print "Sorry, you did not guess the number. The number was " + number and end the game.
Your application should use java.util.Scanner to take user input, java.util.Random to generate the random target number, and control structures (loops and if-else statements) to manage the game logic.
Please write your implementation of this game in the space provided below.
Answer:
javaCopy code
import java.util.Scanner;
import java.util.Random;

public class GuessTheNumber {
public static void main(String[] args) {
Random rand = new Random();
int number = rand.nextInt(100) + 1;

Scanner scanner = new Scanner(System.in);

for (int i = 0; i < 10; i++) {
System.out.println("Enter your guess:");
int guess = scanner.nextInt();

if (guess < number) {
System.out.println("Too low! Try again.");
} else if (guess > number) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You've guessed the number.");
return;
}
}

System.out.println("Sorry, you did not guess the number. The number was " + number);
}
}

Your task is to implement a Java application that performs the following steps:
Generates an array of 10 randomly generated integers between 1 and 100 (inclusive).
Prints this array of numbers to the console.
Prompts the user to sort the numbers in ascending order (from lowest to highest value).
After the user types 'sort' and presses enter, the program should sort the array and print the sorted array to the console.
You should use java.util.Scanner to take user input, java.util.Random to generate the random integers, and java.util.Arrays.sort method to sort the array.
Here is a skeleton of what your code should look like:
javaCopy code
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;

public class SortArray {
public static void main(String[] args) {
Random rand = new Random();
int[] numbers = new int[10];

// Fill the array with random numbers and print the array

// Ask the user to sort the array

// Sort the array and print the sorted array
}
}

Please complete the implementation of this program in the space provided below.
Answer:
javaCopy code
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;

public class SortArray {
public static void main(String[] args) {
Random rand = new Random();
int[] numbers = new int[10];

// Fill the array with random numbers
for (int i = 0; i < numbers.length; i++) {
numbers[i] = rand.nextInt(100) + 1;
}

// Print the array
System.out.println("Array: " + Arrays.toString(numbers));

// Ask the user to sort the array
System.out.println("Type 'sort' and press Enter to sort the array.");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();

if (input.equalsIgnoreCase("sort")) {
// Sort the array
Arrays.sort(numbers);

// Print the sorted array
System.out.println("Sorted array: " + Arrays.toString(numbers));
} else {
System.out.println("Invalid input. Exiting the program.");
}
}
}


A Java Program illustrating the use of the Static Initializer Block
Here's an example Java program that demonstrates the use of a static initializer block:
public class StaticInitializerExample {
private static int numInstances;

static {
numInstances = 0;
System.out.println("Static initializer block executed.");
}

public StaticInitializerExample() {
numInstances++;
System.out.println("Constructor called. Number of instances: " + numInstances);
}

public static void main(String[] args) {
StaticInitializerExample instance1 = new StaticInitializerExample();
StaticInitializerExample instance2 = new StaticInitializerExample();
}
}

In this program, we have a class called StaticInitializerExample that contains a static initializer block. The static initializer block is defined using the static keyword and is executed when the class is loaded by the JVM before any object of the class is created.
Inside the static initializer block, we initialize the numInstances variable to 0 and print a message to indicate that the block has been executed.
The class also has a constructor that increments the numInstances variable each time an instance of StaticInitializerExample is created. The constructor also prints the current number of instances.
In the main method, we create two instances of StaticInitializerExample. When the program is executed, the static initializer block is executed first, setting numInstances to 0 and printing the corresponding message. Then, the constructor is called twice, incrementing numInstances and printing the number of instances each time.
When you run the program, the output will be:
javascriptCopy code
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.