Форум программистов, компьютерный форум, киберфорум
Ruby
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.71/7: Рейтинг темы: голосов - 7, средняя оценка - 4.71
1 / 1 / 0
Регистрация: 05.10.2018
Сообщений: 18
1

Write a program so that you can interact with your baby dragon.

16.03.2019, 10:45. Показов 1311. Ответов 4
Метки ruby (Все метки)

Author24 — интернет-сервис помощи студентам
Write a program so that you can interact with your baby dragon. You should be able to enter commands like feed and walk, and have those methods be called on your dragon. Of course, since what you are inputting are just strings, you will have to have some sort of method dispatch, where your program checks which string was entered, and then calls the appropriate method.


Автор вроде-бы просит написать целую программу, которая будет контактировать с его программой, но, как я понял, нужно всё-таки написать метод , вызывающий другие методы с помощью ввода.

Вся программа, кроме метода dispatch- программа автора.

Ruby
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
class Dragon
 
  def initialize name
    @name = name
    @asleep = false
    @stuffInBelly     = 10  # He's full.
    @stuffInIntestine =  0  # He doesn't need to go.
 
    puts @name + ' is born.'
  end
 
  def feed
    puts 'You feed ' + @name + '.'
    @stuffInBelly = 10
    passageOfTime
  end
 
  def walk
    puts 'You walk ' + @name + '.'
    @stuffInIntestine = 0
    passageOfTime
  end
 
  def putToBed
    puts 'You put ' + @name + ' to bed.'
    @asleep = true
    3.times do
      if @asleep
        passageOfTime
      end
      if @asleep
        puts @name + ' snores, filling the room with smoke.'
      end
    end
    if @asleep
      @asleep = false
      puts @name + ' wakes up slowly.'
    end
  end
 
  def toss
    puts 'You toss ' + @name + ' up into the air.'
    puts 'He giggles, which singes your eyebrows.'
    passageOfTime
  end
 
  def rock
    puts 'You rock ' + @name + ' gently.'
    @asleep = true
    puts 'He briefly dozes off...'
    passageOfTime
    if @asleep
      @asleep = false
      puts '...but wakes when you stop.'
    end
  end
 
 
  # "private" means that the methods defined here are
  # methods internal to the object.  (You can feed
  # your dragon, but you can't ask him if he's hungry.)
 
  def hungry?
    # Method names can end with "?".
    # Usually, we only do this if the method
    # returns true or false, like this:
    @stuffInBelly <= 2
  end
 
  def poopy?
    @stuffInIntestine >= 8
  end
 
  def passageOfTime
    if @stuffInBelly > 0
      # Move food from belly to intestine.
      @stuffInBelly     = @stuffInBelly     - 1
      @stuffInIntestine = @stuffInIntestine + 1
    else  # Our dragon is starving!
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'                                                        
      end
      puts @name + ' is starving!  In desperation, he ate YOU!'
      exit  # This quits the program.
      private
    end
 
    if @stuffInIntestine >= 10
      @stuffInIntestine = 0
      puts 'Whoops!  ' + @name + ' had an accident...'
    end
 
    if hungry?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + '\'s stomach grumbles...'
    end
 
    if poopy?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + ' does the potty dance...'
    end
  end
 
end
 
def dispatch
command = gets.chomp
methodHash  = Hash.new
methodHash['feed']  = feed
 
if command == 'feed'
  puts methodHash['feed']
end
 
  end
 
 
 
 
pet = Dragon.new 'Norbert'
 
pet.dispatch



Почему-то в консоли этот метод называют приватным


Код
C:\Users\Женя>classDragon
Norbert is born.
Traceback (most recent call last):
C:/Users/Женя/classDragon.rb:129:in `<main>': private method `dispatch' called for #<Dragon:0x00000000030be020> (NoMethodError)
Did you mean?  display
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
16.03.2019, 10:45
Ответы с готовыми решениями:

Write a program to perform the following operations
Write a program to perform the following operations: a) Create an integer array of floating point...

Write a program that performs operations
Write a program that performs operations: a) Create an array, each element of which contains the...

TASK: Write a program that displays the multiplication table 10 by 10 as follows: 1 2 3 … 2 4 6 … 3 6 9 …
Write a program that displays the multiplication table 10 by 10 as follows: 1 2 3 … 2 4 6 … 3...

Write a program which accepts two real numbers, asks whether the user requires a rounded or truncated result
задача на языке c# (ох уже эти экзамены) Write a program which accepts two real numbers, asks...

4
Фрилансер
3705 / 2077 / 567
Регистрация: 31.05.2009
Сообщений: 6,683
16.03.2019, 21:00 2
Оно пишет NoMethodError - ведь dispatch вообще не метод класса, он вне его
0
1 / 1 / 0
Регистрация: 05.10.2018
Сообщений: 18
19.03.2019, 15:46  [ТС] 3
Write a program so that you can interact with your baby dragon. You should be able to enter commands like feed and walk, and have those methods be called on your dragon. Of course, since what you are inputting are just strings, you will have to have some sort of method dispatch, where your program checks which string was entered, and then calls the appropriate method.


Автор вроде-бы просит написать целую программу, которая будет контактировать с его программой, но, как я понял, нужно всё-таки написать метод , вызывающий другие методы с помощью ввода.

Вся программа, кроме метода dispatch- программа автора.

Ruby
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
  def initialize name
    @name = name
    @asleep = false
    @stuffInBelly     = 10  # He's full.
    @stuffInIntestine =  0  # He doesn't need to go.
 
    puts @name + ' is born.'
  end
 
  def feed
    puts 'You feed ' + @name + '.'
    @stuffInBelly = 10
    passageOfTime
  end
 
  def walk
    puts 'You walk ' + @name + '.'
    @stuffInIntestine = 0
    passageOfTime
  end
 
  def putToBed
    puts 'You put ' + @name + ' to bed.'
    @asleep = true
    3.times do
      if @asleep
        passageOfTime
      end
      if @asleep
        puts @name + ' snores, filling the room with smoke.'
      end
    end
    if @asleep
      @asleep = false
      puts @name + ' wakes up slowly.'
    end
  end
 
  def toss
    puts 'You toss ' + @name + ' up into the air.'
    puts 'He giggles, which singes your eyebrows.'
    passageOfTime
  end
 
  def rock
    puts 'You rock ' + @name + ' gently.'
    @asleep = true
    puts 'He briefly dozes off...'
    passageOfTime
    if @asleep
      @asleep = false
      puts '...but wakes when you stop.'
    end
  end
 
 
  # "private" means that the methods defined here are
  # methods internal to the object.  (You can feed
  # your dragon, but you can't ask him if he's hungry.)
 
  def hungry?
    # Method names can end with "?".
    # Usually, we only do this if the method
    # returns true or false, like this:
    @stuffInBelly <= 2
  end
 
  def poopy?
    @stuffInIntestine >= 8
  end
 
  def passageOfTime
    if @stuffInBelly > 0
      # Move food from belly to intestine.
      @stuffInBelly     = @stuffInBelly     - 1
      @stuffInIntestine = @stuffInIntestine + 1
    else  # Our dragon is starving!
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'                                                        
      end
      puts @name + ' is starving!  In desperation, he ate YOU!'
      exit  # This quits the program.
      private
    end
 
    if @stuffInIntestine >= 10
      @stuffInIntestine = 0
      puts 'Whoops!  ' + @name + ' had an accident...'
    end
 
    if hungry?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + '\'s stomach grumbles...'
    end
 
    if poopy?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + ' does the potty dance...'
    end
  end
def dispatch
command = gets.chomp
methodHash  = Hash.new
while command != 'exit'
if command == 'feed'
  puts feed
 else 
  if command == 'walk'
    puts walk
  
  else 
  if command == 'putToBed'
    puts putToBed
 
  else 
  if command == 'toss'
    puts toss
 
  else 
  if command == 'rock'
    puts rock
  end
end
 end
  end
   end
  
end
end
end
pet = Dragon.new 'Norbert'
 
pet.dispatch




Помогите разобраться с этим методом dispatch
Вот, что выдаёт консоль

Ruby
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
eed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Whoops!  Norbert had an accident...
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Whoops!  Norbert had an accident...
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Whoops!  Norbert had an accident...
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Norbert does the potty dance...
 
You feed Norbert.
Whoops!  Norbert had an accident...
 
You feed Norbert.

и так бесконечно, если ввести 'feed'

 Комментарий модератора 

Правила форума

4. Порядок создания тем.
4.13 Если на ваш вопрос долгое время нет ответа, уточните его, приведите дополнительные сведения, которые могут помочь участникам форума решить вашу проблему.
4.14 Чтобы "поднять" тему в разделе и поиске по форуму, используйте осмысленные сообщения, например "Тема/проблема/задача актуальна". Если вы чего-то достигли в решении проблемы на этот момент, сообщите об этом.

5. Запреты и ограничения.
5.5 Запрещено размещать тему в нескольких подразделах одного раздела одновременно (кросспостинг), а также дублировать тему в одном разделе.


Добавлено через 59 минут
Ruby
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
def dispatch
command = gets.chomp
 
command = ''
while command != 'exit'
if command == 'feed'
  puts feed
 else 
  if command == 'walk'
    puts walk
  
  else 
  if command == 'putToBed'
    puts putToBed
 
  else 
  if command == 'toss'
    puts toss
 
  else 
  if command == 'rock'
    puts rock
  end
end
 end
  end
   end
  
end
end


в теории тут всё должно работать, но если ввести
Ruby
1
feed
она ничего не выводит:

Norbert is born.
feed
0
the hardway first
Эксперт JS
2461 / 1836 / 906
Регистрация: 05.06.2015
Сообщений: 3,603
19.03.2019, 15:56 4
RoflanGenius, у вас команда один раз до цикла запрашивается и потом постоянно проверяется одно и то же.
Ruby
1
2
3
4
5
6
7
8
9
10
11
12
13
def dispatch
  command = gets.chomp
  methodHash = Hash.new # what is it?
 
  # `command` не изменяется в теле цикла - бесконечный цикл
  while command != 'exit'
    if command == 'feed'
      puts feed
      else
      # code omit for bravity
    end
  end
end
Каким образом у вас ключевое слово private оказалось в методе Dragon#passageOfTime?

Для ясности возьмём оригинал и мне кажется автор имел ввиду просто сделать вспомогательный метод, например #dispatch, но не изменять класс Dragon, и вашу сумасшедшую ветку if...else (хотя тут явно напрашивается case, как минимум)
Ruby
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
class Dragon
 
  def initialize name
    @name = name
    @asleep = false
    @stuffInBelly     = 10  # He's full.
    @stuffInIntestine =  0  # He doesn't need to go.
 
    puts @name + ' is born.'
  end
 
  def feed
    puts 'You feed ' + @name + '.'
    @stuffInBelly = 10
    passageOfTime
  end
 
  def walk
    puts 'You walk ' + @name + '.'
    @stuffInIntestine = 0
    passageOfTime
  end
 
  def putToBed
    puts 'You put ' + @name + ' to bed.'
    @asleep = true
    3.times do
      if @asleep
        passageOfTime
      end
      if @asleep
        puts @name + ' snores, filling the room with smoke.'
      end
    end
    if @asleep
      @asleep = false
      puts @name + ' wakes up slowly.'
    end
  end
 
  def toss
    puts 'You toss ' + @name + ' up into the air.'
    puts 'He giggles, which singes your eyebrows.'
    passageOfTime
  end
 
  def rock
    puts 'You rock ' + @name + ' gently.'
    @asleep = true
    puts 'He briefly dozes off...'
    passageOfTime
    if @asleep
      @asleep = false
      puts '...but wakes when you stop.'
    end
  end
 
  private
 
  # "private" means that the methods defined here are
  # methods internal to the object.  (You can feed
  # your dragon, but you can't ask him if he's hungry.)
 
  def hungry?
    # Method names can end with "?".
    # Usually, we only do this if the method
    # returns true or false, like this:
    @stuffInBelly <= 2
  end
 
  def poopy?
    @stuffInIntestine >= 8
  end
 
  def passageOfTime
    if @stuffInBelly > 0
      # Move food from belly to intestine.
      @stuffInBelly     = @stuffInBelly     - 1
      @stuffInIntestine = @stuffInIntestine + 1
    else  # Our dragon is starving!
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + ' is starving!  In desperation, he ate YOU!'
      exit  # This quits the program.
    end
 
    if @stuffInIntestine >= 10
      @stuffInIntestine = 0
      puts 'Whoops!  ' + @name + ' had an accident...'
    end
 
    if hungry?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + '\'s stomach grumbles...'
    end
 
    if poopy?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + ' does the potty dance...'
    end
  end
 
end # class Dragon
 
def dispatch(pet, command)
  if command == 'feed'
    pet.feed
  else
    if command == 'walk'
      pet.walk
    else
      if command == 'putToBed'
        pet.putToBed
      else
        if command == 'toss'
          pet.toss
        else
          if command == 'rock'
            pet.rock
          end
        end
      end
    end
  end
end
 
pet = Dragon.new 'Norbert'
 
while 'exit' != command = gets.chomp
  dispatch(pet, command)
end
0
1 / 1 / 0
Регистрация: 05.10.2018
Сообщений: 18
19.03.2019, 16:05  [ТС] 5
Можете не отвечать , я разобрался

Ruby
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
class Dragon
 
  def initialize name
    @name = name
    @asleep = false
    @stuffInBelly     = 10  # He's full.
    @stuffInIntestine =  0  # He doesn't need to go.
 
    puts @name + ' is born.'
  end
 
  def feed
    puts 'You feed ' + @name + '.'
    @stuffInBelly = 10
    passageOfTime
  end
 
  def walk
    puts 'You walk ' + @name + '.'
    @stuffInIntestine = 0
    passageOfTime
  end
 
  def putToBed
    puts 'You put ' + @name + ' to bed.'
    @asleep = true
    3.times do
      if @asleep
        passageOfTime
      end
      if @asleep
        puts @name + ' snores, filling the room with smoke.'
      end
    end
    if @asleep
      @asleep = false
      puts @name + ' wakes up slowly.'
    end
  end
 
  def toss
    puts 'You toss ' + @name + ' up into the air.'
    puts 'He giggles, which singes your eyebrows.'
    passageOfTime
  end
 
  def rock
    puts 'You rock ' + @name + ' gently.'
    @asleep = true
    puts 'He briefly dozes off...'
    passageOfTime
    if @asleep
      @asleep = false
      puts '...but wakes when you stop.'
    end
  end
 
 
  # "private" means that the methods defined here are
  # methods internal to the object.  (You can feed
  # your dragon, but you can't ask him if he's hungry.)
 
  def hungry?
    # Method names can end with "?".
    # Usually, we only do this if the method
    # returns true or false, like this:
    @stuffInBelly <= 2
  end
 
  def poopy?
    @stuffInIntestine >= 8
  end
 
  def passageOfTime
    if @stuffInBelly > 0
      # Move food from belly to intestine.
      @stuffInBelly     = @stuffInBelly     - 1
      @stuffInIntestine = @stuffInIntestine + 1
    else  # Our dragon is starving!
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'                                                        
      end
      puts @name + ' is starving!  In desperation, he ate YOU!'
      exit  # This quits the program.
      private
    end
 
    if @stuffInIntestine >= 10
      @stuffInIntestine = 0
      puts 'Whoops!  ' + @name + ' had an accident...'
    end
 
    if hungry?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + '\'s stomach grumbles...'
    end
 
    if poopy?
      if @asleep
        @asleep = false
        puts 'He wakes up suddenly!'
      end
      puts @name + ' does the potty dance...'
    end
  end
def dispatch
 
 
command = ''
 
while command != 'exit'
  command = gets.chomp
if command == 'feed'
  puts feed
 else 
  if command == 'walk'
    puts walk
  
  else 
  if command == 'putToBed'
    puts putToBed
 
  else 
  if command == 'toss'
    puts toss
 
  else 
  if command == 'rock'
    puts rock
  end
end
 end
  end
   end
  
end
end
end
pet = Dragon.new 'Norbert'
 
pet.dispatch
Добавлено через 6 минут
Я даже не заметил ваш ответ, но всё равно спасибо. Автор не рассказывал о методе
сase
0
19.03.2019, 16:05
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
19.03.2019, 16:05
Помогаю со студенческими работами здесь

NORMALIZE ME BABY...
Нaскoлькo вы нoрмaлизуете вaши бaзы дaнных? Сегoдня прoспoрил с индийским тoвaришем чaс. Ему лень...

No rule to make target 'C:/Program', needed by 'release/Program.o'. Stop
Доброго времени суток! Помогите, пожалуйста, исправить ошибку No rule to make target...

Запускается FactoryMethod.Program вместо AbstractFactory.Program - как исправить?
Запускается FactoryMethod.Program вместо AbstractFactory.Program - как исправить?

Предотвратить или перехватить ошибку DOMException: play() failed because the user didn't interact
Добрый день, подскажите плиииз! Надо проиграть звук. Написал для этого функцию-&quot;обертку&quot; над...

Ошибка cannot write a property that has no write specifiers
TTabItem* newtab; newtab = new TTabItem(this); newtab-&gt;TabControl = TabControl1; //Тут ошибка...

После запуска program.exe ничего не происходит, то есть program.exe запустилась, а дальше код не выполняется
int main() { system(&quot;&quot;C:\\Program Files (X86)\\Files\\program.exe&quot;&quot;); cout &lt;&lt; &quot;Hi&quot; &lt;&lt;...


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

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru