You should read more about dependency injection.
Your Class shouldn't be tightly coupled with other classes. Dependencies can be provided to objects at multiple levels according to the need.
- Using constructor/setter if it is a field.
- Using method parameters if the scope is just in a method.
In your case as soon as you say:-
Scanner scanner = new Scanner(System.in);
Now your code is fully coupled with System.in
stream. Instead you should inject this as a parameter to your method in below format.
public double input(InputStream inputStream) {
double result = 0;
Scanner scanner = new Scanner(inputStream);
if (scanner.hasNextDouble()) {
result = scanner.nextDouble();
} else {
System.out.print("Please, type numbers!\n");
}
return result;
}
Now from your main code you can call it with System.in
. From your test class you call it with any InputStream. Mostly we use a mock/stub
for it.
Note:- Above it just an example, and can be change according to need.