Hello guys, consider this piece of code:
import java.util.Scanner;
public class Recap {
public static void main(String[] args) {
Statistics total = new Statistics();
System.out.println("Enter numbers:");
while (true) {
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
if (number != -1) {
total.addNumber(number);
}
else {
sc.close();
break;
}
}
System.out.println(total.sum());
}
}
I have a question:
When using the Scanner class to take inputs, is it best practice to declare the Scanner object inside the loop itself or outside the loop please (Does that make a difference?)
Talking of best practice, say we write the following class:
public class Statistics {
private int count;
private int sum = 0;
public Statistics() {
int count = 0;
}
public void addNumber(int number) {
count++;
sum += number;
}
public int getCount() {
return count;
}
public int sum() {
return sum;
}
public double average() {
return (double) sum / count;
}
}
say I need to call the sum() method inside another method, like a toString() method. Normally, is it best to prefix the sum() method being called inside the toString() method by the this keyword? or we can just omit it for better readability ? Because behind the scenes, the compiler will implicitly use it anyway