I have some code in which multiple methods use the keyboard, and are called consecutively in the main method. The exercise I am doing specifically asks for the 4 separate methods so I cannot put them altogether. Originally, I used keyboard.close()
at the end of each method, but this would cause a NoSuchElementException
when the second method is run, regardless of the order they're called. By removing the keyboard.close()
, the code now works, however I now have warnings for a resource leak as the keyboard isn't closed. Can anyone point me to a way to close the inputs without getting an error? Any help would be greatly appreciated.
import java.util.*;
public class CurrencyConverter {
static double money;
static double xr;
//Running
public static void main(String[] args)
{
requestAmount();
requestRate();
displayResult();
}
//Retrieving amount of money to be exchanged based on user input
public static void requestAmount()
{
System.out.println("Please enter quanitity of money to be exchanged:");
Scanner keyboard = new Scanner(System.in);
money = keyboard.nextDouble();
}
//Retrieving exchange rate from user input
public static void requestRate()
{
System.out.println("Please enter exchange rate:");
Scanner keyboard = new Scanner(System.in);
xr = keyboard.nextDouble();
}
//Converting currency
public static double conversionCalculator(double moneyIn, double xrIn)
{
return moneyIn*xrIn;
}
//Display amount of converted currency
public static void displayResult()
{
System.out.println("Amount of currency post-conversion = " + conversionCalculator(money, xr));
}
}
/*
Design and implement a program that converts a sum of money to a different
currency. The amount of money to be converted, and the exchange rate, are
entered by the user. The program should have separate methods for:
• obtaining the sum of money from the user;
• obtaining the exchange rate from the user;
• making the conversion;
• displaying the result.
*/