1. Enter 20 numbers from the keyboard, save them to the list and sort them into three other lists: the number is divided by 3 ( x % 3 == 0 ), divided by 2 ( x % 2 == 0 ) and all others. Numbers that are divided into 3 and 2 at the same time, for example, 6, fall into both lists.
  2. The printList method should display all the elements of the list on a new line.
  3. Using the printList method, printList these three lists. First, the one for x % 3 , then the one for x % 2 , then the last one.

I made 1 and 2 points. How to make 3 points?

 public class Solution { public static void main(String[] args) throws Exception { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> list3 = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); ArrayList<Integer> list32 = new ArrayList<Integer>();` while(true) { String s = rd.readLine(); if (s.isEmpty()) break; int x = Integer.parseInt(s); if (x % 3 == 0) { list3.add(x); printList(list3); } else if (x % 2 == 0) { list2.add(x); printList(list2); } else if ((x % 3 == 0) && (x % 2 == 0)) { list32.add(x); printList(list32); } } } public static void printList(List<Integer> list) { //напишите тут ваш код System.out.println(list); } } 

    1 answer 1

    The first item you did wrong:
    1. You can enter more or less than 20 numbers.
    2. The number in the list2 does not always add when necessary, but in the list32 nothing at all hits, and its name is strange - there is no hint of such a task in the task.

    By code itself:
    1. Constructions while (true) should be avoided.
    2. InputStreamReader and BufferedReader must be closed after use.

    The result is something like this:

     public static void main(String[] args) { ArrayList<Integer> list3 = new ArrayList<>(); ArrayList<Integer> list2 = new ArrayList<>(); ArrayList<Integer> others = new ArrayList<>(); try (BufferedReader rd = new BufferedReader(new InputStreamReader(System.in))) { for (int i = 0; i < 20; i++) { String line = rd.readLine(); int number = Integer.parseInt(line); if (number % 3 == 0) { list3.add(number); } if (number % 2 == 0) { list2.add(number); } if (number % 3 != 0 && number % 2 != 0) { others.add(number); } } } catch (IOException e) { } printList(list3); printList(list2); printList(others); } public static void printList(List<Integer> list) { System.out.println(list); } 
    • and what is bad while(true) ? - pavel
    • @pavel if you really need an infinite loop, then this is not bad. But I do not remember in practice such situations. As a rule, while still has a condition to exit. And if this condition is located somewhere inside the body of a while , then it makes reading the code more difficult. And in the first second, only after seeing while (true) , it is fair to think that the cycle is really infinite. - Regent
    • Thank you for correcting! @Regent - UlanZauspov