R
R
Redrik052021-08-27 02:00:18
Java
Redrik05, 2021-08-27 02:00:18

How does Scanner scanner work as a method parameter?

Good afternoon. There is a problem on code decomposition. Spaghetti should be removed from the main method and scattered over other methods. One of them looks like this:

public static void convert(Scanner scanner, double moneyBeforeSalary) {
        
        double rateUSD = 78.5;
        double rateEUR = 85;
        double rateJPY = 0.74;
        
        System.out.println("Ваши сбережения: " + moneyBeforeSalary + " RUB");
        System.out.println("В какую валюту хотите конвертировать? Доступные варианты: 1 - USD, 2 - EUR, 3 - JPY.");
        int currency = scanner.nextInt();
        
        if (currency == 1) {
            System.out.println("Ваши сбережения в долларах: " + moneyBeforeSalary / rateUSD);
        } else if (currency == 2) {
            System.out.println("Ваши сбережения в евро: " + moneyBeforeSalary / rateEUR);
        } else if (currency == 3) {
            System.out.println("Ваши сбережения в иенах: " + moneyBeforeSalary / rateJPY);
        } else {
            System.out.println("Неизвестная валюта");
        }
    }


The task statement says:
The convert method will be used to convert currencies. You will find the parameters for it in the precode. It should take as arguments the balance of the account and a variable of complex type scanner - this will avoid duplicating the code for reading the currency selection.


I don't understand how the Scanner scanner should work here, and what should be passed in its place when calling the method.

Question: how to change the code so that it is correct, and how to correctly call the method so that it works?

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey〒., 2021-08-27
@Redrik05

The Scanner object is simply passed to the method, see where it reads from.
You can pass system input like this:
convert(new Scanner(System.in), 1.55)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question