Criando um Programa Interativo com Scanner
Agora, vamos criar um programa interativo que permite ao usuário inserir dois valores long e, em seguida, compará-los usando o método Long.compare().
Para isso, usaremos a classe Scanner, que nos permite ler a entrada do usuário.
- Atualize o arquivo
LongCompare.java com o seguinte código:
import java.util.Scanner;
public class LongCompare {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Long Compare Tool!");
System.out.println("This program compares two long values that you enter.");
System.out.println("----------------------------------------");
// Prompt the user to enter the first number
System.out.print("Enter the first long number: ");
long firstNumber;
// Use a try-catch block to handle invalid input
try {
firstNumber = scanner.nextLong();
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid long number.");
return;
}
// Prompt the user to enter the second number
System.out.print("Enter the second long number: ");
long secondNumber;
// Use a try-catch block to handle invalid input
try {
secondNumber = scanner.nextLong();
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid long number.");
return;
}
// Compare the two numbers
int result = Long.compare(firstNumber, secondNumber);
// Display the result
System.out.println("\nResult of comparing " + firstNumber + " and " + secondNumber + ":");
if (result > 0) {
System.out.println(firstNumber + " is greater than " + secondNumber);
} else if (result < 0) {
System.out.println(firstNumber + " is less than " + secondNumber);
} else {
System.out.println(firstNumber + " is equal to " + secondNumber);
}
// Close the Scanner to release resources
scanner.close();
}
}
Compile e execute o programa:
javac LongCompare.java && java LongCompare
Você deve ver uma saída semelhante a esta (seus resultados dependerão dos valores que você inserir):
Welcome to the Long Compare Tool!
This program compares two long values that you enter.
----------------------------------------
Enter the first long number: 1500
Enter the second long number: 2000
Result of comparing 1500 and 2000:
1500 is less than 2000
Tente executar o programa novamente com entradas diferentes:
javac LongCompare.java && java LongCompare
Por exemplo, se você inserir 5000 e 3000:
Welcome to the Long Compare Tool!
This program compares two long values that you enter.
----------------------------------------
Enter the first long number: 5000
Enter the second long number: 3000
Result of comparing 5000 and 3000:
5000 is greater than 3000
Neste exemplo, estamos usando a classe Scanner para ler a entrada do usuário. Também estamos usando blocos try-catch para lidar com possíveis erros se o usuário inserir uma entrada inválida.
O método Scanner.nextLong() lê um valor long do usuário e, em seguida, usamos o método Long.compare() para comparar os dois valores inseridos pelo usuário.
Este programa interativo demonstra como você pode usar o método Long.compare() em uma aplicação do mundo real onde a entrada do usuário está envolvida.