Java Online Compiler
Example: Maximum Handshakes Calculator in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Maximum Handshakes Calculator import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter the number of people System.out.print("Enter the number of people: "); // Step 3: Read the number of people from the user int numberOfPeople = scanner.nextInt(); // Step 4: Validate input to ensure it's non-negative if (numberOfPeople < 0) { System.out.println("Number of people cannot be negative."); } else { // Step 5: Calculate the maximum number of handshakes using the formula // The formula is n * (n - 1) / 2, where n is the number of people. // This represents "n choose 2" combinations. long maxHandshakes = (long) numberOfPeople * (numberOfPeople - 1) / 2; // Step 6: Print the result System.out.println("Maximum number of handshakes: " + maxHandshakes); } // Step 7: Close the scanner to prevent resource leaks scanner.close(); } }
Output
Clear
ADVERTISEMENTS