Форум программистов, компьютерный форум, киберфорум
Java для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/7: Рейтинг темы: голосов - 7, средняя оценка - 5.00
0 / 0 / 0
Регистрация: 18.11.2020
Сообщений: 2

Текстовое меню и сабменю

18.11.2020, 22:01. Показов 1431. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Уважаемые эксперты,
Помогите ламеру с созданием текстового меню, а именно перейти из сабменю обратно в меню, нажав на клавишу 4:
заранее спасибо,
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
import java.util.Scanner;
 
public class MenuProgramm {
 
    public static void main(String[] args) {
        
        
                System.out.println("*** Main Menu***");
                System.out.println("1 - Set activity");
            System.out.println("2 - Multiple activity" );
            System.out.println("3 - Print activity");
            System.out.println("4 - Set details");
            System.out.println("5 - Display configurations");
            System.out.println("6 - Quit the program");
            System.out.println("7 - Set minimum details" );
            System.out.println("8 - Set maximum details" );
            boolean quit = false;
        
            int menuItem;
 
do {
     menuItem = in.nextInt();
        
        
            
            switch(menuItem) {
            //case 1: System.out.println("test message1"); break;
            case 2:  System.out.println("test message2"); break;
            case 3:  System.out.println("test message2"); break;
            sorter.printCoinList(); break;
            case 4:  System.out.println("test111"); break;
            case 6:   System.out.println("Bye-bye!"); break;
            case 7:  System.out.println("test message7"); break;
            //////case 8:  System.out.println("test message8"); break;
                
                //////while(menuItem != 6);System.out.println("Switched Back to main menu");break;
            default:
 
                 System.out.println("Invalid choice.");
            }
        }while (menuItem != 4);System.out.print("*** Sub-Menu***");
        System.out.println();
        
        System.out.println ("1 - Action 1");
            
        System.out.println("2 - Action2" );
        
        System.out.println("3 - action3"); 
        
        [B]System.out.println("4 - Return to main menu"); [/B]
         //////////int menuItem1;
        do {
 
            
            menuItem = in.nextInt();
 
            switch (menuItem) {
 
            case 1:
 
                  System.out.println("You've chosen item #1");
 
                  // do something...
 
                  break;
 
            case 2:
 
                  System.out.println("You've chosen item #2");
 
                  // do something...
 
                  break;
 
            case 3:
 
                  System.out.println("You've chosen item #3");
 
                  // do something...
 
                  break;
 
            case 4: 
 
                
                System.out.println("");
                
            default:
 
                  System.out.println("Invalid choice.");
 
            }
 
      } while(menuItem != 4); 
        menuItem = in.nextInt();
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
18.11.2020, 22:01
Ответы с готовыми решениями:

Текстовое меню вынести в отдельный класс
Текстовое меню вынести в отдельный класс, а в main() добавить создание экземпляра класса Menu(). Вот код меню. package com.company; ...

Составить текстовое меню
составить текстовое меню, в котором при выборе первого пункта вычисляется косинус введенного числа, при выборе другого пункта - синус. при...

вопрос по кнопкам и сабменю
Доброго времени суток, друзья. Проблема: Есть горизонтальное меню из трёх(допустим) кнопок (button) с анимацией UP и OVER. ...

3
3582 / 2182 / 571
Регистрация: 02.09.2015
Сообщений: 5,510
19.11.2020, 01:29
Можно выделить метод:
Java
1
private static void subMenu() {}
И вызывать его из основного.
0
0 / 0 / 0
Регистрация: 18.11.2020
Сообщений: 2
19.11.2020, 02:06  [ТС]
напиши пожалста!!!!
0
Эксперт функциональных языков программированияЭксперт Java
 Аватар для korvin_
4575 / 2774 / 491
Регистрация: 28.04.2012
Сообщений: 8,779
19.11.2020, 16:22
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
import java.util.*;
 
final class Main {
 
    public static void main(String[] args) {
        final var list = new ArrayList<String>();
        final var map = new HashMap<String, String>();
 
        final var menu = Menu.menu()
                .quitOn("q", "Quit")
                .item("1", "List", Menu.menu()
                        .quitOn("b", "Back")
                        .prompt("list")
                        .item("1", "Add item", Command.input("list.add", list::add))
                        .item("2", "Delete item", Command.input("list.del", list::remove))
                        .item("3", "Show all items", ui -> list.forEach(ui::send)))
                .item("2", "Map", Menu.menu()
                        .quitOn("b", "Back")
                        .prompt("map")
                        .item("1", "Put key-value pair", Command.input("map.put", s -> {
                            final var pair = parseMapEntry(s);
                            map.put(pair.getKey(), pair.getValue());
                        }))
                        .item("2", "Delete value by key", Command.input("map.del", map::remove))
                        .item("3", "Show all key-value pairs", ui -> map.forEach((k, v) -> ui.send(String.format("%s: %s", k, v)))))
                .build();
 
        final var ui = new CLI("\t", "> ", new Scanner(System.in), System.out);
 
        menu.interactWith(ui);
    }
 
    private static Map.Entry<String, String> parseMapEntry(String s) {
        final var tokens = s.split("\\s+", 2);
        if (tokens.length != 2) {
            throw new IllegalArgumentException("invalid input");
        }
        return new AbstractMap.SimpleImmutableEntry<>(tokens[0], tokens[1]);
    }
}
App.java
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
import java.util.List;
 
final class App {
 
    interface UserInterface {
 
        void show(List<String> commands);
 
        void send(String data);
 
        String receive(String name);
    }
 
    interface Routine {
 
        void interactWith(UserInterface ui);
    }
 
    interface RoutineBuilder<T extends Routine> {
 
        T build();
    }
 
    private App() {
        throw new UnsupportedOperationException("Module class");
    }
}


Menu.java
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
import java.util.*;
import java.util.stream.Collectors;
 
final class Menu implements App.Routine {
 
    static Builder menu() {
        return new Builder();
    }
 
    private final String prompt;
    private final String quitCmd;
    private final String quitTitle;
    private final List<String> itemTitles;
    private final Map<String, App.Routine> items;
 
    private Menu(Builder b) {
        prompt = b.prompt;
        quitCmd = b.quitCmd;
        quitTitle = b.quitTitle;
        itemTitles = itemTitles(b.items);
        items = items(b.items);
    }
 
    @Override
    public void interactWith(App.UserInterface ui) {
        while (true) {
            ui.show(itemTitles);
 
            try {
                final var command = ui.receive(prompt).trim();
                if (command.equals(quitCmd)) {
                    return;
                }
 
                final var subroutine = items.get(command);
                if (subroutine == null) {
                    ui.send("Unknown command: " + command);
                    continue;
                }
 
                subroutine.interactWith(ui);
            } catch (Exception e) {
                ui.send("ERROR: " + e.toString());
            }
        }
    }
 
    private List<String> itemTitles(List<Item> items) {
        int maxCmdLength = Math.max(
                quitCmd.length(),
                items.stream().mapToInt(item -> item.cmd.length()).max().orElse(0)
        );
 
        final var titles = new ArrayList<String>(items.size()+1);
        for (var item : items) {
            titles.add(title(item.cmd, item.title, maxCmdLength));
        }
        titles.add(title(quitCmd, quitTitle, maxCmdLength));
        return titles;
    }
 
    private Map<String, App.Routine> items(List<Item> items) {
        return items.stream().collect(Collectors.toUnmodifiableMap(
                item -> item.cmd,
                item -> item.routine
        ));
    }
 
    private String title(String cmd, String title, int cmdLength) {
        if (cmd.length() < cmdLength) {
            cmd += spaces(cmdLength - cmd.length());
        }
        return String.format("%s - %s", cmd, title);
    }
 
    private static String spaces(int count) {
        final var spaces = new char[count];
        Arrays.fill(spaces, ' ');
        return new String(spaces);
    }
 
    static final class Builder implements App.RoutineBuilder<Menu> {
 
        private final List<Item> items;
 
        private String prompt = "";
        private String quitCmd;
        private String quitTitle;
 
        private Builder() {
            this.items = new ArrayList<>();
        }
 
        Builder prompt(String p) {
            Objects.requireNonNull(p, "prompt");
            prompt = p;
            return this;
        }
 
        Builder quitOn(String command, String title) {
            quitCmd = notEmpty(command, "command");
            quitTitle = notEmpty(title, "title");
            requireNoDuplicates(command);
            return this;
        }
 
        Builder item(String command, String title, App.RoutineBuilder<?> routine) {
            return item(command, title, routine.build());
        }
 
        Builder item(String command, String title, App.Routine routine) {
            if (command.equals(quitCmd)) {
                throw new DuplicateCommand(command);
            }
            requireNoDuplicates(command);
            items.add(new Item(command, title, routine));
            return this;
        }
 
        @Override
        public Menu build() {
            notEmpty(quitCmd, "quitCommand");
            notEmpty(quitTitle, "quitTitle");
            return new Menu(this);
        }
 
        private void requireNoDuplicates(String cmd) {
            for (var item : items) {
                if (cmd.equals(item.cmd)) {
                    throw new DuplicateCommand(cmd);
                }
            }
        }
 
        private String notEmpty(String s, String name) {
            Objects.requireNonNull(s, name);
            s = s.trim();
            if (s.isEmpty()) {
                throw new EmptyStringArgument(name);
            }
            return s;
        }
    }
 
    static final class DuplicateCommand extends RuntimeException {
 
        private DuplicateCommand(String cmd) {
            super(cmd);
        }
    }
 
    static final class EmptyStringArgument extends RuntimeException {
 
        private EmptyStringArgument(String name) {
            super(name);
        }
    }
 
    private static final class Item {
 
        private final String cmd;
        private final String title;
        private final App.Routine routine;
 
        private Item(String cmd, String title, App.Routine routine) {
            this.cmd = cmd;
            this.title = title;
            this.routine = routine;
        }
    }
}


Command.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.function.Consumer;
 
final class Command {
 
    static App.Routine action(Runnable r) {
        return ui -> r.run();
    }
 
    static App.Routine input(String prompt, Consumer<String> c) {
        return ui -> c.accept(ui.receive(prompt));
    }
}


CLI.java
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
import java.io.PrintStream;
import java.util.List;
import java.util.Scanner;
 
final class CLI implements App.UserInterface {
 
    private final String indent;
    private final String promptSuffix;
    private final Scanner in;
    private final PrintStream out;
 
    CLI(String indent, String promptSuffix, Scanner in, PrintStream out) {
        this.indent = indent;
        this.promptSuffix = promptSuffix;
        this.in = in;
        this.out = out;
    }
 
    @Override
    public void show(List<String> commands) {
        out.println();
        commands.forEach(cmd -> out.println(indent + cmd));
        out.println();
    }
 
    @Override
    public void send(String data) {
        out.println(data);
    }
 
    @Override
    public String receive(String name) {
        out.print(name + promptSuffix);
        return in.nextLine();
    }
}
Миниатюры
Текстовое меню и сабменю  
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
19.11.2020, 16:22
Помогаю со студенческими работами здесь

Оператор множественного выбора: создать текстовое меню
Створіть текстове меню, .в якому при виборі першого пункту обчислюється косинус введеного числа, при виборі другого пункту – синус, при...

Составить базу данных Домоуправление, имеющую текстовое меню
составить базу данных, имеющих текстовое менюи содержащую информацию: &quot;домоуправление&quot; -улицы -номер дома -этажность ...

Создать базу данных, имеющую текстовое меню и данные об одноклассниках
«Одноклассники» - фамилия - месяц и год рождения - номер телефона Составить типизированный файл. Данные вводить в файл. Производить...

1 клик открываем сабменю 2клика переходим по ссылке
Подскажите как мне реализовать такую вещь: Есть двухуровневое меню(хотя в принципе не важно 2 или 3 уровня меню), необходимо при 1...

Дана матрица N*N. Создать текстовое меню для возможности выбора решения любого из 2 пунктов
Добрый день! Дана матрица N*N. Создать текстовое меню для возможности выбора решения любого из 3 пунктов. Создать максим. возможные по...


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

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru