Hey guys and girls,
I have no idea where I am wrong with my solution. The code works perfectly fine. I tried to declare and initialize the lists seperately (e.g. ArrayList<Integer> list = new ArrayList<Integer>();) followed by value-input through the methods in the following lines. In this case IntelliJ IDEA tells me that the initialization is redundant. Even then the condition does not come true.
Best regards,
Mathis
package com.codegym.task.task07.task0713;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/*
Playing Javarella
1. Enter 20 numbers from the keyboard, save them in a list, and then sort them to three other lists:
Numbers divisible by 3 (x%3==0), numbers divisible by 2 (x%2==0), and all other numbers.
Numbers simultaneously divisible by 3 and 2 (for example 6) go into both lists.
The order in which the lists are declared is very important.
2. The printList method should display each list item on a new line.
3. Using the printList method, display these three lists. First, the list for x%3, then the list for x%2, and then the last list.
Requirements:
1. Declare and immediately initialize 4 ArrayList<Integer> variables. The first list will be the main one. The other lists will be supplementary.
2. Read 20 numbers from the keyboard and add them to the main list.
3. Add to the first supplementary list all numbers in the main list that are divisible by 3.
4. Add to the second supplementary list all numbers in the main list that are divisible by 2.
5. Add to the third supplementary list all the remaining numbers from the main list.
6. The printList method should display each element of the passed list on a new line.
7. The program should display the three supplementary lists using the printList method.
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = initializeIntList();
ArrayList<Integer> list2 = sortList(list, 3);
ArrayList<Integer> list3 = sortList(list, 2);
ArrayList<Integer> listRest = sortList(list, 0);
printList(list2);
printList(list3);
printList(listRest);
}
public static ArrayList<Integer> initializeIntList() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i<20; i++) {
list.add(Integer.parseInt(reader.readLine()));
}
reader.close();
return list;
}
public static ArrayList<Integer> sortList(ArrayList<Integer> list, int divisor) {
ArrayList<Integer> listNew = new ArrayList<Integer>();
for (Integer temp: list) {
if (divisor!=0) {
if (temp%divisor==0) {
listNew.add(temp);
}
} else {
if (temp%2!=0 && temp%3!=0) {
listNew.add(temp);
}
}
}
return listNew;
}
public static void printList(List<Integer> list) {
for (Integer temp: list) {
System.out.println(temp);
}
}
}