Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.63/8: Рейтинг темы: голосов - 8, средняя оценка - 4.63
15 / 1 / 0
Регистрация: 09.12.2018
Сообщений: 39

Заменить все контейнеры на ArrayList, и переписать программу таким образом, чтобы она успешно с ним работала

30.12.2018, 19:06. Показов 1750. Ответов 14
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package ua.lviv.lgs;
 
import java.time.Month;
import java.util.Scanner;
 
public class Task_2 {
 
 
    static class Season {
 
 
        public enum Seasons {
 
            WINTER,
            SPRING,
            SUMMER,
            AUTUMN;
 
 
            public enum Month {
 
                JANUARY(31, "WINTER"),
                    FEBRUARY(28, "SPRING"),
                    MARCH(31, "SPRING"),
                    APRIL(30, "SPRING"),
                    MAY(31, "SUMMER"),
                    JUNE(30, "SUMMER"),
                    JULY(31, "SUMMER"),
                    AUGUST(31, "AUTUMN"),
                    SEPTEMBER(30, "AUTUMN"),
                    OCTOBER(31, "AUTUMN"),
                    NOVEMBER(30, "WINTER"),
                    DECEMBER(31, "WINTER");
 
                public int getInDays() {
                    return inDays;
                }
 
                public int setInDays(int inDays) {
                    return this.inDays = inDays;
                }
 
                public String getInSeasons() {
                    return inSeasons;
                }
 
                public void setInSeasons(String inSeasons) {
                    this.inSeasons = inSeasons;
                }
 
                public  int inDays;
 
                public String inSeasons;
 
                Month(int inDays, String inSeasons) {
 
                    this.inDays = inDays;
                    this.inSeasons = inSeasons;
 
                }
            }
        }
        public int inDays;
        public Month month;
        public Seasons inSeasons;
 
 
        public Season(Month month, Seasons inSeasons, int inDays) {
            this.month = month;
            this.inSeasons = inSeasons;
            this.inDays = inDays;
 
        }
 
 
 
 
        class ProcessingMonth {
            Scanner sc = new Scanner(System.in);
 
            /**
             * 
             * @return month equalized with the console entered month
             */
            public Month readMonth() {
                while (true) {
                    if (!(sc.hasNextInt())) {
                        String s = sc.nextLine().trim();
                        for (Month month: Month.values()) {
                            if (s.equalsIgnoreCase(month.name())) {
                                return month;
                            }
                        }
                        System.out.println("The word you entered is not \nthe name of the month, try again");
                        sc = new Scanner(System.in);
                    } else {
                        int m = sc.nextInt();
                        if (m > 12 || m < 1) {
                            System.out.println("You entered the wrong month, try again.");
                            sc = new Scanner(System.in);
                        } else {
                            for (Month month: Month.values()) {
                                if (m == month.ordinal() + 1) {
                                    return month;
                                }
                            }
                        }
                    }
                }
            }
 
            /**
             * 
             * @param month console entered month
             */
            public void sameSeasonMonths(Month month) {
                Seasons season;
                if (month.ordinal() >= 8 && month.ordinal() <= 10) {
                    season = Seasons.AUTUMN;
                } else if (month.ordinal() >= 2 && month.ordinal() <= 4) {
                    season = Seasons.SPRING;
                } else if (month.ordinal() >= 5 && month.ordinal() <= 7) {
                    season = Seasons.SUMMER;
                } else {
                    season = Seasons.WINTER;
                }
                switch (season) {
                    case AUTUMN:
                        for (Month months: Month.values()) {
                            if (months.ordinal() == month.ordinal() || months.ordinal() < 8 || months.ordinal() > 10) {} else {
                                System.out.println(months);
                            }
                        }
                        break;
                    case SPRING:
                        for (Month months: Month.values()) {
                            if (months.ordinal() == month.ordinal() || months.ordinal() < 2 || months.ordinal() > 4) {} else {
                                System.out.println(months);
                            }
                        }
                        break;
                    case SUMMER:
                        for (Month months: Month.values()) {
                            if (months.ordinal() == month.ordinal() || months.ordinal() < 5 || months.ordinal() > 7) {} else {
                                System.out.println(months);
                            }
                        }
                        break;
                    case WINTER:
                        for (Month months: Month.values()) {
                            if (months.ordinal() == month.ordinal() || months.ordinal() < 11 && months.ordinal() > 1) {} else {
                                System.out.println(months);
                            }
                        }
                        break;
                }
            }
 
            public void isEvenNumberOfDays(Month month, int days) {
                if (days % 2 == 0) {
                    System.out.println(month.name() + " has an even number of days.");
                } else {
                    System.out.println(month.name() + " has an odd number of days.");
                }
            }
        }
 
        class MethodsForComparison {
 
            public void withSpecifiedNumberOfDays(int specifiedNumber) {
                for (Month m: Month.values()) {
                    if (m.inDays == specifiedNumber) {
                        System.out.println(m.toString());
                    }
                }
            }
 
            public void withGreaterNumberOfDays(int specifiedNumber) {
                for (Month m: Month.values()) {
                    if (m.inDays > specifiedNumber) {
                        System.out.println(m.toString());
                    }
                }
            }
            public void withSmallerNumberOfDays(int specifiedNumber) {
                for (Month m: Month.values()) {
                    if (m.inDays < specifiedNumber) {
                        System.out.println(m.toString());
                    }
                }
            }
        }
 
        static class Main {
 
 
            public void withSpecifiedNumberOfDays(int specifiedNumber) {
                for (Month m: Month.values()) {
                    if (m.inDays == specifiedNumber) {
                        System.out.println(m.toString());
                    }
                }
            }
 
            public void withGreaterNumberOfDays(int specifiedNumber) {
                String s = null;
 
                for (Month m: Month.values()) {
                    if (m.inDays > specifiedNumber) {
                        System.out.println(m.toString());
                        s = m.toString();
 
                    }
                }
                if (s == null) {
                    System.out.println("not more Great month");
                }
 
            }
 
            public void withSmallerNumberOfDays(int specifiedNumber) {
 
                String s = null;
                for (Month m: Month.values()) {
                    if (m.inDays < specifiedNumber) {
                        System.out.println(m.toString());
                        s = m.toString();
                    }
                }
                if (s == null) {
                    System.out.println("not more Small month");
                }
 
            }
 
            public void nexSeasons(Month month) {
                int i = 0;
                String[] d = {
                    "WINTER",
                    "SPRING",
                    "SUMMER",
                    "AUTUMN"
                };
                for (Seasons seas: Seasons.values()) {
                    i++;
                    if (month.inSeasons.equals(seas.name())) {
                        System.out.println("next seasons is " + d[i + 1]);
                    }
                }
 
            }
 
            public void pastSeasons(Month month) {
                int i = 0;
                String[] d = {
                    "WINTER",
                    "SPRING",
                    "SUMMER",
                    "AUTUMN"
                };
                for (Seasons seas: Seasons.values()) {
                    i++;
                    if (month.inSeasons.equals(seas.name())) {
                        System.out.println("next past is " + d[i - 1]);
                    }
                }
            }
 
            public void evenMonth() {
 
                for (Month d: Month.values()) {
 
 
                    if (d.inDays % 2 == 0) {
                        System.out.println(d.name() + " day = " + d.inDays);
                    }
 
                }
 
            }
 
            public void oddMonth() {
                for (Month d: Month.values()) {
 
 
                    if (d.inDays % 2 == 1) {
                        System.out.println(d.name() + " day = " + d.inDays);
                    }
 
                }
 
 
            }
 
            public static void main(String[] args) {
 
                ProcessingMonth month = new ProcessingMonth();
 
                System.out.println("take your pick :(only number)\n1 - Check for a month\n2 - show on display all months with the same time of year\n3 - show on display if put the console month has an even number of days\n4 - show on display all months that have the equal number of days\n5 - show on display all months that have more Great days\n6 - show on display all months that have fewer days\n7 - show on display Display the next season\n8 - show on display past season\n9 - show on display all months that have an odd number of days\n10 - show on display or put the console has an even number of month days\n11 - exit   ");
 
 
 
                int number;
                boolean flag = true;
                Main monthMain = new Main();
 
 
                while (flag) {
                    Scanner scan = new Scanner(System.in);
                    if (scan.hasNextInt()) {
 
                        number = scan.nextInt();
 
                        if (number > 11 || number < 1) {
                            System.out.println("---------------------------------------------------------------------------");
                            System.out.println("your choice is incorrect");
                            System.out.println("---------------------------------------------------------------------------");
                        }
 
 
 
                        switch (number) {
                            case 1:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("1 - Check for a month");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
 
                                    month.readMonth();
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 2:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("2 - show on display all months with the same time of year");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
                                    month.sameSeasonMonths(month.readMonth());
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 3:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("3 - show on display if put the console month has an even number of days");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
                                    month.isEvenNumberOfDays(month.readMonth(), inDays);
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 4:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("4 - show on display all months that have the equal number of days");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
                                    monthMain.withSpecifiedNumberOfDays(month.readMonth().inDays);
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 5:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("5 - show on display all months that have more Great days");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
                                    monthMain.withGreaterNumberOfDays(month.readMonth().inDays);
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 6:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("6 - show on display all months that have fewer days");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
                                    monthMain.withSmallerNumberOfDays(month.readMonth().inDays);
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 7:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("7 - show on display the next season");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
                                    monthMain.nexSeasons(month.readMonth());
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 8:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("8 - show on display past season");
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("enter the month");
                                    monthMain.nexSeasons(month.readMonth());
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 9:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("9 - show on display all months that have an odd number of days");
                                    System.out.println("---------------------------------------------------------------------------");
                                    monthMain.oddMonth();
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 10:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("10 - show on display or put the console has an even number of month days");
                                    System.out.println("---------------------------------------------------------------------------");
                                    monthMain.evenMonth();
 
                                    System.out.println("Select the next step");
                                    break;
                                }
                            case 11:
                                {
                                    System.out.println("---------------------------------------------------------------------------");
                                    System.out.println("11 - exit");
                                    System.out.println("---------------------------------------------------------------------------");
 
                                    flag = false;
                                    break;
                                }
                        }
                    } else {
                        System.out.println("---------------------------------------------------------------------------");
                        System.out.println("error invalid input");
                        System.out.println("---------------------------------------------------------------------------");
                    }
 
 
 
                }
            }
 
        }
    }
 
}
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
30.12.2018, 19:06
Ответы с готовыми решениями:

Изменить программу таким образом, чтобы она работала с массивом вещественных чисел
Пытаюсь решить задачу, взятую из одного курса на MVA. Дан исходный код: static void Main(string args) { ...

Переписать программу, чтобы она работала не с текстом, а числами
Постараюсь быть максимально конкретным. Прога на языке Си. Здесь (проверено) работающая нормально прога с символами. В одном документе...

Работа с процедурами. Переписать программу, чтобы она работала через процедуры
Всем привет. Передо мной стоит задача написать программу используя процедуры и нет. Без процедур: var Form1: TForm1; a: array...

14
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
30.12.2018, 19:28
какие контейнеры?
0
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7390 / 4817 / 1246
Регистрация: 30.03.2015
Сообщений: 13,667
Записей в блоге: 29
30.12.2018, 20:07

Не по теме:

Цитата Сообщение от Kostyshyn Посмотреть сообщение
ua.lviv.lgs;
Львовский Гос ... эээ... С?



Kostyshyn,
программа отлично подойдет для главы Рефакторинг какой-нибудь книги по джава - чтобы показать страшное дублирование кода и потом постепенно избавляться от него, демонстрируя уменьшение размера программы с сохранением функциональности и повышением читаемости.

Что планируется менять - перечисления или пару локальных массивов?
0
15 / 1 / 0
Регистрация: 09.12.2018
Сообщений: 39
30.12.2018, 21:58  [ТС]
enum на ArrayList
0
 Аватар для NiceJacket
109 / 89 / 25
Регистрация: 02.06.2018
Сообщений: 259
30.12.2018, 22:53
Честно говоря, в код не вчитывался,но что-то мне подсказывает, что для этого потребуется тупо переписать всю программу..
А чем мотивирован выбор arraylist'a ?
0
15 / 1 / 0
Регистрация: 09.12.2018
Сообщений: 39
31.12.2018, 00:14  [ТС]
Мотивирован он тем что сегодня на уроке обьясняли его и вкачестве практики сказали переделать из enum'a в arraylist.

Добавлено через 1 минуту
Welemir1, logos it academy
0
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
31.12.2018, 12:05
чет хреново учат в этой академии
0
230 / 199 / 71
Регистрация: 21.10.2016
Сообщений: 449
31.12.2018, 12:16
Kostyshyn, что написано в меню в переводе с ломаного английского на русский?
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
 
public class Task2 {
 
    public static void main(String[] args) {
        System.out.println("take your pick (only number):\n" 
            + "1 - Check for month\n"
            + "2 - Show on display all months with the same time of year\n"
            + "3 - Show on display if put the console month has an even namber of days\n"
            + "4 - Show on display all months that have the equal number of days\n"
            + "5 - Show on display all months that have more Great days\n"
            + "6 - Show on display all months that have fewer days\n"
            + "7 - Show on display Display the next season\n"
            + "8 - Show on display past season\n"
            + "9 - Show on display all months that have an odd number of days\n"
            + "10 - Show on display or put the console has an even number of month days\n"
            + "11 - Exit\n");
 
        int input;
        boolean exit = false;
        while (!exit) {
            Scanner scan = new Scanner(System.in);
            input = scan.nextInt();
            switch (input) {
                case 1: 
                    System.out.println("Check for a month");
                    break;
                case 11:
                    exit = true;
                    break;
                default:
                    System.out.println("Error: invalid input");
                    break;
            }
        }
    }
}
Много непонятного. Много вопросов.
1
15 / 1 / 0
Регистрация: 09.12.2018
Сообщений: 39
31.12.2018, 12:19  [ТС]
С украинского
0
230 / 199 / 71
Регистрация: 21.10.2016
Сообщений: 449
31.12.2018, 13:07
Kostyshyn, переведи меню, по пунктам. Что нужно то?
0
15 / 1 / 0
Регистрация: 09.12.2018
Сообщений: 39
31.12.2018, 13:22  [ТС]
Эта задача по enum
Кликните здесь для просмотра всего текста
Написать консольную программу для работы с Enums. Создать Энума Сезоны, в котором

объявить такие константы: Зима, Весна, Лето, Осень. Создать Энума Луне, в котором

создать 12 констант- месяца года (Январь, Февраль .. декабрь), объявить переменную дни, и

переменную сезон типа Сезон, как поле Энума. Создать конструктор с определенными

параметрами в Энума Луне, в который в качестве параметров передать переменную дни и сезон. описать

getters к данным полей (дни, сезоны). Создать консольное меню, в котором реализовать

следующие пункты:

Проверить есть ли такой месяц (месяц вводим с консоли, предусмотреть, чтобы регистр

букв была не важным)

Вывести все месяцы с таким же временем года

Вывести все месяцы которые имеют такое же количество дней

Вывести на экран все месяцы которые имеют меньшее количество дней

Вывести на экран все месяцы которые имеют большее количество дней

Вывести на экран следующую время года

Вывести на экран предыдущую время года

Вывести на экран все месяцы которые имеют четное количество дней

Вывести на экран все месяцы которые имеют нечетное количество дней

Вывести на экран или введен с консоли месяц имеет четное количество дней
ее надо переделать используя arraylist
0
230 / 199 / 71
Регистрация: 21.10.2016
Сообщений: 449
31.12.2018, 13:28
А зачем enum засунул в Task2?
0
15 / 1 / 0
Регистрация: 09.12.2018
Сообщений: 39
31.12.2018, 13:34  [ТС]
Я это сделал чтобы не переключать с проекта на проект, но забыл закомментировать
0
230 / 199 / 71
Регистрация: 21.10.2016
Сообщений: 449
31.12.2018, 22:24
Цитата Сообщение от Kostyshyn Посмотреть сообщение
Написать консольную программу для работы с Enums. Создать Энума Сезоны, в котором
объявить такие константы: Зима, Весна, Лето, Осень.
Java
1
2
3
4
5
6
7
public enum Season {
 
    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}
Добавлено через 20 минут
Цитата Сообщение от Kostyshyn Посмотреть сообщение
Создать Энума Луне, в котором
создать 12 констант- месяца года (Январь, Февраль .. декабрь), объявить переменную дни, и
переменную сезон типа Сезон, как поле Энума. Создать конструктор с определенными
параметрами в Энума Луне, в который в качестве параметров передать переменную дни и сезон. описать
getters к данным полей (дни, сезоны).
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public enum Month {
 
    JANUARY(31, Season.WINTER),
    FEBRUARY(28, Season.WINTER),
    MARCH(31, Season.SPRING),
    APRIL(30, Season.SPRING),
    MAY(31, Season.SPRING),
    JUNE(30, Season.SUMMER),
    JULY(31, Season.SUMMER),
    AUGUST(31, Season.SUMMER),
    SEPTEMBER(30, Season.AUTUMN),
    OCTOBER(31, Season.AUTUMN),
    NOVEMBER(30, Season.AUTUMN),
    DECEMBER(31, Season.WINTER);
 
    private Month(int days, Season season) {
        this.days = days;
        this.season = season;
    }
 
    private int days;
 
    private Season season;
 
    public int getDays() {
        return days;
    }
 
    public Season getSeason() {
        return season;
    }
 
    // тест
    public static void main(String[] args) {
        System.out.println(Month.JANUARY.getDays());
        System.out.println(Month.JANUARY.getSeason());
    }
}
Bash
1
2
3
const@mate ~/progs $ java Month
31
WINTER
Добавлено через 8 часов 24 минуты
Всем с наилучшими пожеланиями в Новом Году!!!
1
230 / 199 / 71
Регистрация: 21.10.2016
Сообщений: 449
02.01.2019, 18:56
Лучший ответ Сообщение было отмечено Kostyshyn как решение

Решение

Пункт 10 не сделал. Ну там еще почистить кое-где надо.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import java.util.*;
 
public class ProcessingMonth {
 
    public static void main(String[] args) {
        new ProcessingMonth().run();
    }
 
    private void run() {
        Month month;
        int menueItemChosen;
        boolean exit = false;
 
        while (!exit) {
            month = readMonth();
            menueItemChosen = readMenueItemChosen();
 
            switch (menueItemChosen) {
                case 1:
                    MonthUtil.check(month);    // Проверить есть ли такой месяц
                    break;
                case 2:
                    MonthUtil.printMonthsWithSameSeasonAs(month);    //Вывести все месяцы с таким же временем года
                    break;
                case 3:
                    MonthUtil.printMonthsAsLongAs(month); //Вывести все месяцы которые имеют такое же количество дней
                    break;
                case 4:
                    MonthUtil.printMonthsShorterThan(month);   // Вывести на экран все месяцы которые имеют меньшее количество дней
                    break;
                case 5:
                    MonthUtil.printMonthsLongerThan(month);    // Вывести на экран все месяцы которые имеют большее количество дней
                    break;
                case 6:
                    MonthUtil.printNextSeasonFor(month);    // Вывести на экран следующую время года
                    break;
                case 7:
                    MonthUtil.printPreviousSeasonFor(month);    // Вывести на экран предыдущую время года
                    break;
                case 8:
                    MonthUtil.printMonthsWithEvenNumberOfDays();    // Вывести на экран все месяцы которые имеют четное количество дней
                    break;
                case 9:
                    MonthUtil.printMonthsWithOddNumberOfDays();    // Вывести на экран все месяцы которые имеют нечетное количество дней
                    break;
                case 10:
                    MonthUtil.method();    // Вывести на экран или введен с консоли месяц имеет четное количество дней???
                    break;
                case 11:
                    exit = true;
                    break;
                default:
                    System.out.println("Error: invalid input");
                    break;
            }
        }
    }
 
    private void printStartingMessage() {
        System.out.println();
        System.out.println("Enter any month. For example:");
        System.out.println("=> January");
        System.out.print("=> ");
    }
 
    private Month readMonth() {
        Scanner scanner = new Scanner(System.in);
        String inputString;
        Month month;
        while(true) {
            printStartingMessage();
            inputString = scanner.nextLine().trim();
            try {
                month = Month.valueOf(inputString.toUpperCase());
                return month;
            }
            catch (IllegalArgumentException e) {
                System.out.println("Invalid enter detected");
            }
        }
    }
 
    private void printMenueMessage() {
        System.out.println("\ntake your pick (only number):\n" 
            + "1 - Check for month\n"
            + "2 - Show on display all months with the same time of year\n"
            + "3 - Show on display all months that have the equal number of days\n"
            + "4 - Show on display all months that have fewer days\n"
            + "5 - Show on display all months that have more Great days\n"
            + "6 - Show on display Display the next season\n"
            + "7 - Show on display past season\n"
            + "8 - Show on display or put the console has an even number of month days\n"
            + "9 - Show on display all months that have an odd number of days\n"
            + "10 - Show on display if put the console month has an even namber of days\n"
            + "11 - Exit\n");
        System.out.print("=> ");
    }
 
    private int readMenueItemChosen() {
        printMenueMessage();
        Scanner sc = new Scanner(System.in);
        return sc.nextInt();
    }
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import java.util.*;
 
public class MonthUtil {
 
    // 1
    public static void check(Month month) {
        boolean monthExists = false;
        for (Month m : Month.values()) {
            if (m.equals(month)) {
                monthExists = true;
            }
        }
 
        if (monthExists) {
            System.out.println(month + " do exists");
        }
        else {
            System.out.println("There isn't such month as " + month);
        }
    }
 
    // 2
    public static void printMonthsWithSameSeasonAs(Month month) {
        Collection<Month> monthCollection = new ArrayList<>();
        Season season = month.getSeason();
        for (Month m : Month.values()) {
            if (m.getSeason().equals(season)) {
                monthCollection.add(m);
            }
        }
 
        System.out.print("\nThere are ");
        for (Month m : monthCollection) {
            System.out.print(m + " ");
        }
        System.out.println("in " + season);
    }
 
    // 3
    public static void printMonthsAsLongAs(Month month) {
        Collection<Month> monthCollection = new ArrayList<>();
        int days = month.getDays();
        for (Month m : Month.values()) {
            if (m.getDays() == days) {
                monthCollection.add(m);
            }
        }
 
        System.out.print("\nThere are " + days + " days in");
        for (Month m : monthCollection) {
            System.out.print(" " + m);
        }
        System.out.println(".");
    }
 
    // 4
    public static void printMonthsShorterThan(Month month) {
        Collection<Month> monthCollection = new ArrayList<>();
        int days = month.getDays();
        for (Month m : Month.values()) {
            if (m.getDays() < days && !m.equals(month)) {
                monthCollection.add(m);
            }
        }
 
        if (month.equals(Month.FEBRUARY)) {
            System.out.println("\nThere aren't months shorter than february");
        }
        else {
            System.out.print("\nThere are ");
            for (Month m : monthCollection) {
                System.out.print(m + " ");
            }
            System.out.println("shorter than " + month);
        }
    }
 
    //5
    public static void printMonthsLongerThan(Month month) {
        Collection<Month> monthCollection = new ArrayList<>();
        int days = month.getDays();
        for (Month m : Month.values()) {
            if (m.getDays() > days && !m.equals(month)) {
                monthCollection.add(m);
            }
        }
 
        if (monthCollection.size() == 0) {
            System.out.println("\nThere aren't months longer than " + month);
        }
        else {
            System.out.print("\nThere are ");
            for (Month m : monthCollection) {
                System.out.print(m + " ");
            }
            System.out.println("longer than " + month);
        }
    }
 
    // 6
    public static void printNextSeasonFor(Month month) {
        System.out.print("Next season for " + month + " is ");
        switch (month) {
            case DECEMBER:
            case JANUARY:
            case FEBRUARY:
                System.out.println(Season.SPRING);
                break;
            case MARCH:
            case APRIL:
            case MAY:
                System.out.println(Season.SUMMER);
                break;
            case JUNE:
            case JULY:
            case AUGUST:
                System.out.println(Season.AUTUMN);
                break;
            case SEPTEMBER:
            case OCTOBER:
            case NOVEMBER:
                System.out.println(Season.WINTER);
                break;
            default:
                System.out.println("Invalid month entered");
                break;
        }
    }
 
    // 7
    public static void printPreviousSeasonFor(Month month) {
        System.out.print("Previous season for " + month + " is ");
        switch (month) {
            case DECEMBER:
            case JANUARY:
            case FEBRUARY:
                System.out.println(Season.AUTUMN);
                break;
            case MARCH:
            case APRIL:
            case MAY:
                System.out.println(Season.WINTER);
                break;
            case JUNE:
            case JULY:
            case AUGUST:
                System.out.println(Season.SPRING);
                break;
            case SEPTEMBER:
            case OCTOBER:
            case NOVEMBER:
                System.out.println(Season.SUMMER);
                break;
            default:
                System.out.println("Invalid month entered");
                break;
        }
    }
 
    // 8
    public static void printMonthsWithEvenNumberOfDays() {
        Collection<Month> monthCollection = new ArrayList<>();
        for (Month m : Month.values()) {
            if (m.getDays() % 2 == 0) {
                monthCollection.add(m);
            }
        }
 
        for (Month m : monthCollection) {
            System.out.print(m + " ");
        }
        System.out.println("have even number of days");
    }
 
    // 9
    public static void printMonthsWithOddNumberOfDays() {
        Collection<Month> monthCollection = new ArrayList<>();
        for (Month m : Month.values()) {
            if (m.getDays() % 2 == 1) {
                monthCollection.add(m);
            }
        }
 
        for (Month m : monthCollection) {
            System.out.print(m + " ");
        }
        System.out.println("have odd number of days");
    }
 
    // 10
    public static void method() {
        System.out.println("method #10");
    }
}
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
02.01.2019, 18:56
Помогаю со студенческими работами здесь

Модифицируйте программу таким образом, чтобы она выводила название чисел в диапазоне от 1 до 99
program TWELFTH; uses crt; var a,b,c,d,e:integer; begin write('Введите число от 1го до 10ти'); readln(a); a:=1;

Отредактировать текст таким образом, чтобы все знаки препинания располагались в начале, за ним следовали цифры
Дано некоторый текст. Отредактировать его таким образом, чтобы все знаки препинания располагались в начале строки, за ним следовали цифра,...

Написать программу, реализующую способ передачи книги таким образом, чтобы она переходя от друга к другу побывала в руках у каждого
Помогите вкурить в задание, кому не влом. Т.е. к примеру наше N = 100, значит у чела с книгой друзей N/2 = 50. Соответственно K...

Переписать функцию sqrt, чтобы она работала с большими числами
желательно что бы корень извлекался из строки и возвращался результат в виде строки

Изменить программу таким образом, чтобы все большие буквы заменялись на символ
Помогите, пожалуйста, изменить код, чтобы выполнялись такие задания: 1 программа: Все большие буквы заменить на символ ‘#’. 2...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
15
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Первый деплой
lagorue 16.01.2026
Не спеша развернул своё 1ое приложение в kubernetes. А дальше мне интересно создать 1фронтэнд приложения и 2 бэкэнд приложения развернуть 2 деплоя в кубере получится 2 сервиса и что-бы они. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит: токи, напряжения и их 1 и 2 производные при t = 0;. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru