Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 09.12.2022
Сообщений: 5

Код на Dart, ООП

03.02.2023, 14:46. Показов 644. Ответов 10

Студворк — интернет-сервис помощи студентам
Вот такой код:

Code
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
class Person {
  String name;
  int age;
  double weight;
  double height;
  DateTime dateOfBirth;
  String address;
 
  Person({
    required this.name,
    required this.age,
    required this.weight,
    required this.height,
    required this.dateOfBirth,
    required this.address,
  });
 
  void setName(String name) {
    this.name = name;
  }
 
  String getName() {
    return this.name;
  }
 
  void setAge(int age) {
    this.age = age;
  }
 
  int getAge() {
    return this.age;
  }
 
  void setWeight(double weight) {
    this.weight = weight;
  }
 
  double getWeight() {
    return this.weight;
  }
 
  void setHeight(double height) {
    this.height = height;
  }
 
  double getHeight() {
    return this.height;
  }
 
  void setDateOfBirth(DateTime dateOfBirth) {
    this.dateOfBirth = dateOfBirth;
  }
 
  DateTime getDateOfBirth() {
    return this.dateOfBirth;
  }
 
  void setAddress(String address) {
    this.address = address;
  }
 
  String getAddress() {
    return this.address;
  }
}
 
class Employee extends Person {
  double salary;
  DateTime joinDate;
  int experience;
 
  Employee({
    required name,
    required age,
    required weight,
    required height,
    required dateOfBirth,
    required address,
    required this.salary,
    required this.joinDate,
    required this.experience,
  }) : super(
    name: name,
    age: age,
    weight: weight,
    height: height,
    dateOfBirth: dateOfBirth,
    address: address,
  );
  void setJoinDate(DateTime joinDate) {
    this.joinDate = joinDate;
  }
 
  DateTime getJoinDate() {
    return this.joinDate;
  }
  void setExperience(int experience) {
    this.experience = experience;
  }
 
  int getExperience() {
    return this.experience;
  }
}
 
class Student extends Person {
  Map<String, int> grades;
  List<String> courses;
 
  Student({
    required name,
    required age,
    required weight,
    required height,
    required dateOfBirth,
    required address,
    required this.grades,
    required this.courses,
  }) : super(
    name: name,
    age: age,
    weight: weight,
    height: height,
    dateOfBirth: dateOfBirth,
    address: address,
  );
 
  void showGrades() {
    print("Grades: ");
    grades.forEach((course, grade) {
      print("$course: $grade");
    });
  }
}
 
  class Professor extends Employee {
  List<Student> students;
  List<String> courses;
 
  Professor({
    required this.students,
    required this.courses,
    required String name,
    required int age,
    required double weight,
    required double height,
    required DateTime dateOfBirth,
    required String address,
    required double salary,
    required DateTime joinDate,
    required int experience,
  }) : super(
    name: name,
    age: age,
    weight: weight,
    height: height,
    dateOfBirth: dateOfBirth,
    address: address,
    salary: salary,
    joinDate: joinDate,
    experience: experience,
  );
 
  void addStudent(Student student) {
    students.add(student);
  }
 
  void addCourse(String course) {
    courses.add(course);
  }
 
  void setGrade(Student student, String course, int grade) {
    int index = courses.indexOf(course);
    String indexStr = index.toString();
    if (index != -1) {
      student.grades[indexStr] = grade;
    }
  }
 
  void showGrades(Student student) {
    for (int i = 0; i < courses.length; i++) {
      print('${courses[i]}: ${student.grades[i]}');
    }
  }
}
 
    void main() {
  Student student1 = Student(
    name: 'Илияс Туймебай',
    age: 20,
    weight: 80.0,
    height: 185.0,
    dateOfBirth: DateTime.now(),
    address: 'Фабричный, Амангельды 30',
    grades: [85, 90, 95],
    courses: ['Математика', 'Химия', 'История'],
  );
 
  Professor professor1 = Professor(
    name: 'Александр Семенович',
    age: 40,
    weight: 70.0,
    height: 170.0,
    dateOfBirth: DateTime.now(),
    address: 'Узынагаш, Акимат',
    salary: 90000.0,
    joinDate: DateTime.now(),
    experience: 20,
    students: [student1],
    courses: ['Математика', 'Химия', 'История'],
  );
 
  professor1.addStudent(student1);
  professor1.addCourse('Физика');
  professor1.setGrade(student1, 'Математика', 88);
  professor1.showGrades(student1);
}
Выдаёт такую ошибку:

Error: The argument type 'List<int>' can't be assigned to the parameter type 'Map<String, int>'.
- 'List' is from 'dart:core'.
- 'Map' is from 'dart:core'.
grades: [85, 90, 95],
^
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
03.02.2023, 14:46
Ответы с готовыми решениями:

Конвертировать код с Python на Dart!
Помогите конвертировать код с Python на Dart from random import randint num = for one in num: if 9 &lt; one &lt; 100: #...

Код на ООП
Подскажите как код сделать в Объектно ориентированном виде? def shell_sort(numbers): n = len(numbers)/2 while n &gt; 0 : ...

переделать код в ООП
Подскажите пожалуйста, как переделать это в ООП? Создать класс time. using System; using System.Collections.Generic; ...

10
93 / 66 / 27
Регистрация: 23.06.2019
Сообщений: 477
03.02.2023, 15:44
Что-то странное.
Обычно вопросы задают и не показывают ни кода, ни ошибки.
А тут все показывают, но ни одного вопроса.
Причем массово.

В чем вопрос? Вроде ошибка четко и ясно показана. В каком месте и что там не так.
У класса параметр map, а при создании экземпляра класса в конструктор передается список.
0
0 / 0 / 0
Регистрация: 09.12.2022
Сообщений: 5
03.02.2023, 16:37  [ТС]
Помоги исправить

Добавлено через 17 минут
vs2019, сможешь исправить в коде?
0
77 / 50 / 29
Регистрация: 21.10.2022
Сообщений: 114
03.02.2023, 17:16
Лучший ответ Сообщение было отмечено ituimebay как решение

Решение

У вас же указана ошибка- пытаетесь инициализировать словарь как список. Нужно типа такого

Code
1
 grades: {'one': 1, 'two': 2, 'three': 3}, //[85, 90, 95],
1
0 / 0 / 0
Регистрация: 09.12.2022
Сообщений: 5
03.02.2023, 17:30  [ТС]
Igor-san, я также попробовал, не работает
0
77 / 50 / 29
Регистрация: 21.10.2022
Сообщений: 114
03.02.2023, 17:54
Цитата Сообщение от ituimebay Посмотреть сообщение
Igor-san, я также попробовал, не работает
Ну так ошибка 'List<int>' can't be assigned to the parameter type 'Map<String, int>' пропала? Значит что то еще не работает?
0
93 / 66 / 27
Регистрация: 23.06.2019
Сообщений: 477
03.02.2023, 17:56
Лучший ответ Сообщение было отмечено ituimebay как решение

Решение

Все прекрасно работает:
s@tn:/tmp$ dart b.dart
Илияс Туймебай
Математика: 85
Химия: 90
История: 95
Физика: null
s@tn:/tmp$


Code
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
class Person {
        String name;
        int age;
        double weight;
        double height;
        DateTime dateOfBirth;
        String address;
 
        Person({
                        required this.name,
                        required this.age,
                        required this.weight,
                        required this.height,
                        required this.dateOfBirth,
                        required this.address,
                        });
 
        void setName(String name) {
                this.name = name;
        }
 
        String getName() {
                return this.name;
        }
 
        void setAge(int age) {
                this.age = age;
        }
 
        int getAge() {
                return this.age;
        }
 
        void setWeight(double weight) {
                this.weight = weight;
        }
 
        double getWeight() {
                return this.weight;
        }
 
        void setHeight(double height) {
                this.height = height;
        }
 
        double getHeight() {
                return this.height;
        }
 
        void setDateOfBirth(DateTime dateOfBirth) {
                this.dateOfBirth = dateOfBirth;
        }
 
        DateTime getDateOfBirth() {
                return this.dateOfBirth;
        }
 
        void setAddress(String address) {
                this.address = address;
        }
 
        String getAddress() {
                return this.address;
        }
}
 
class Employee extends Person {
        double salary;
        DateTime joinDate;
        int experience;
 
        Employee({
                        required name,
                        required age,
                        required weight,
                        required height,
                        required dateOfBirth,
                        required address,
                        required this.salary,
                        required this.joinDate,
                        required this.experience,
                        }) : super(
name: name,
age: age,
weight: weight,
height: height,
dateOfBirth: dateOfBirth,
address: address,
);
        void setJoinDate(DateTime joinDate) {
                this.joinDate = joinDate;
        }
 
        DateTime getJoinDate() {
                return this.joinDate;
        }
        void setExperience(int experience) {
                this.experience = experience;
        }
 
        int getExperience() {
                return this.experience;
        }
}
 
class Student extends Person {
        Map<String, int> grades;
        List<String> courses;
 
        Student({
                        required name,
                        required age,
                        required weight,
                        required height,
                        required dateOfBirth,
                        required address,
                        required this.grades,
                        required this.courses,
                        }) : super(
name: name,
age: age,
weight: weight,
height: height,
dateOfBirth: dateOfBirth,
address: address,
);
 
        void showGrades() {
                print("Grades: ");
                grades.forEach((course, grade) {
                                print("$course: $grade");
                                });
        }
}
 
class Professor extends Employee {
        List<Student> students;
        List<String> courses;
 
        Professor({
                        required this.students,
                        required this.courses,
                        required String name,
                        required int age,
                        required double weight,
                        required double height,
                        required DateTime dateOfBirth,
                        required String address,
                        required double salary,
                        required DateTime joinDate,
                        required int experience,
                        }) : super(
name: name,
age: age,
weight: weight,
height: height,
dateOfBirth: dateOfBirth,
address: address,
salary: salary,
joinDate: joinDate,
experience: experience,
);
 
        void addStudent(Student student) {
                students.add(student);
        }
 
        void addCourse(String course) {
                courses.add(course);
        }
 
        void setGrade(Student student, String course, int grade) {
                int index = courses.indexOf(course);
                String indexStr = index.toString();
                if (index != -1) {
                        student.grades[indexStr] = grade;
                }
        }
 
        void showGrades(Student student) {
                print('${student.name}');
                for (int i = 0; i < courses.length; i++) {
                        print('${courses[i]}: ${student.grades[courses[i]]}');
                }
        }
}
 
void main() {
        Student student1 = Student(
                        name: 'Илияс Туймебай',
                        age: 20,
                        weight: 80.0,
                        height: 185.0,
                        dateOfBirth: DateTime.now(),
                        address: 'Фабричный, Амангельды 30',
                        grades: {'Математика': 85,'Химия': 90,'История': 95},
                        courses: ['Математика', 'Химия', 'История'],
                        );
 
        Professor professor1 = Professor(
                        name: 'Александр Семенович',
                        age: 40,
                        weight: 70.0,
                        height: 170.0,
                        dateOfBirth: DateTime.now(),
                        address: 'Узынагаш, Акимат',
                        salary: 90000.0,
                        joinDate: DateTime.now(),
                        experience: 20,
                        students: [student1],
                        courses: ['Математика', 'Химия', 'История'],
                        );
 
        professor1.addStudent(student1);
        professor1.addCourse('Физика');
        professor1.setGrade(student1, 'Математика', 88);
        professor1.showGrades(student1);
}
0
0 / 0 / 0
Регистрация: 09.12.2022
Сообщений: 5
03.02.2023, 17:56  [ТС]
Igor-san, в консоль выводит вот эту:

Математика: null
Химия: null
История: null
0
93 / 66 / 27
Регистрация: 23.06.2019
Сообщений: 477
03.02.2023, 18:02
У меня все правильно выводит.
s@tn:/tmp$ dart b.dart
Илияс Туймебай
Математика: 85
Химия: 90
История: 95
Физика: null
s@tn:/tmp$

Code
1
2
3
4
5
6
void showGrades(Student student) {
                print('${student.name}');
                for (int i = 0; i < courses.length; i++) {
                        print('${courses[i]}: ${student.grades[courses[i]]}');
                }
        }
print('${courses[i]}: ${student.grades[courses[i]]}');
0
0 / 0 / 0
Регистрация: 09.12.2022
Сообщений: 5
03.02.2023, 18:09  [ТС]
vs2019, setGrade почему-то не работает у меня
0
77 / 50 / 29
Регистрация: 21.10.2022
Сообщений: 114
03.02.2023, 18:15
Напишите так
Java
1
2
3
4
5
6
7
8
9
10
11
  void setGrade(Student student, String course, int grade) {
    if (student.grades.containsKey(course)) {
      student.grades[course] = grade;
    }
  }
 
  void showGrades(Student student) {
    for (int i = 0; i < courses.length; i++) {
      print('${courses[i]}: ${student.grades[courses[i]]}');
    }
  }
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
03.02.2023, 18:15
Помогаю со студенческими работами здесь

Переделать код в ооп
#include&lt;iostream&gt; using namespace std; int main() { int x, n; cout &lt;&lt; &quot;Enter x: &quot;; cin &gt;&gt; x; &lt;&lt; &quot;Enter...

Переделать код в ООП
Помогите переделать код в ООП #include &quot;stdafx.h&quot; #include &lt;stdlib.h&gt; #include&lt;iostream&gt; #include &lt;conio.h&gt; #include...

Изменить код. ООП
изменить код чисто визуально, чтобы не нарушился смысл. RMaxPlus.h #ifndef RMAXPLUS_HPP #define RMAXPLUS_HPP class...

Переделать код в ООП
Здравствуйте! Есть код на Delphi с использованием DirectX: Как сделать с него обьектно-ориентированый код? Ну чтобы было...

Похож ли код на ООП
Здравствуйте, пытаюсь изучить ооп :). Посмотрите пожалуйста похож ли код на ооп хотя бы чуть-чуть, и какие нужно внести изменения, чтоб...


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

Или воспользуйтесь поиском по форуму:
11
Ответ Создать тему
Новые блоги и статьи
Перемещение выделенных строк ТЧ из одного документа в другой
Maks 31.03.2026
Реализация из решения ниже выполнена на примере нетипового документа "ВыдачаОборудованияНаСпецтехнику" с единственной табличной частью "ОборудованиеИКомплектующие" разработанного в конфигурации КА2. . . .
Functional First Web Framework Suave
DevAlt 30.03.2026
Sauve. IO Апнулись до NET10. Из зависимостей один пакет, работает одинаково хорошо как в режиме проекта так и в интерактивном режиме. из сложностей - чисто функциональный подход. Решил. . .
Автоматическое создание документа при проведении другого документа
Maks 29.03.2026
Реализация из решения ниже выполнена на нетиповых документах, разработанных в конфигурации КА2. Есть нетиповой документ "ЗаявкаНаРемонтСпецтехники" и нетиповой документ "ПланированиеСпецтехники". В. . .
Настройка движения справочника по регистру сведений
Maks 29.03.2026
Решение ниже реализовано на примере нетипового справочника "ТарифыМобильнойСвязи" разработанного в конфигурации КА2, с целью учета корпоративной мобильной связи в коммерческом предприятии. . . .
Автозаполнение реквизита при выборе элемента справочника
Maks 27.03.2026
Программный код из решения ниже на примере нетипового документа "ЗаявкаНаРемонтСпецтехники" разработанного в конфигурации КА2. При выборе "Спецтехники" (Тип Справочник. Спецтехника), заполняется. . .
Сумматор с применением элементов трёх состояний.
Hrethgir 26.03.2026
Тут. https:/ / fips. ru/ EGD/ ab3c85c8-836d-4866-871b-c2f0c5d77fbc Первый документ красиво выглядит, но без схемы. Это конечно не даёт никаких плюсов автору, но тем не менее. . . всё может быть. . .
Автозаполнение реквизитов при создании документа
Maks 26.03.2026
Программный код из решения ниже размещается в модуле объекта документа, в процедуре "ПриСозданииНаСервере". Алгоритм проверки заполнения реализован для исключения перезаписи значения реквизита,. . .
Команды формы и диалоговое окно
Maks 26.03.2026
1. Команда формы "ЗаполнитьЗапчасти". Программный код из решения ниже на примере нетипового документа "ЗаявкаНаРемонтСпецтехники" разработанного в конфигурации КА2. В качестве источника данных. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru