Java: ArrayList объявлен как глобальный для класса, но в методе получается пустым
Подскажите пожалуйста, получаю в итоге в методе max пустой список
public class Main {
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
public static int max() {
for (Integer number : numbers) {
if (number > max) {
max = number;
}
}
}
static public void main(String[] args) {
while(scan.hasNextInt()) {
int number = scan.nextInt();
// stop reading
if (number == 0) {
break;
}
numbers.add(number);
}
// Get a result of your code
System.out.println(max());
}
Ответы (1 шт):
Автор решения: Alex Rudenko
→ Ссылка
Во-первых код не компилируется, так как в методе max не определена и не возвращается переменная max, а также в методе main не определена переменная Scanner scan.
Но даже если исправить код, то список вполне может оставаться пустым, так как если сканер не найдёт целое число и его hasNextInt() вернёт false, соответственно никакое число не будет добавлено в список.
Рабочий код:
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
public static Integer max() {
Integer max = null;
for (Integer number : numbers) {
if (max == null || number > max) {
max = number;
}
}
return max;
}
static public void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
int number = scan.nextInt();
// stop reading
if (number == 0) {
break;
}
numbers.add(number);
}
// Get a result of your code
System.out.println("MAX: " + numbers + ": " + max());
}
Примеры работы:
dw
MAX: []: null
4 18 25 19
0
MAX: [4, 18, 25, 19]: 25
123 abcd 987 xyzMAX: [123]: 123