vendredi 28 août 2020

How to set up a small code easter egg in Fortran - randomly selected quotes for error messages

I've created a program which has a user interface to choose an option from a menu. This option is fed to an if statement which redirects it to the correct subroutine. I also have set up a small error message in case of option mistyping.

        else
        write(*,*)''
        write(*,*)''
        write(*,*)''
        write(*,*)'I am sorry, Dave. I am afraid I cannot do that!' 
        write(*,*)''
        write(*,*)''
        write(*,*)''
        write(*,*)' Press enter to return to main menu! '
        read(*,*)
        goto 300
    end if 

And it all works fine. Thing is - HAL9000 has so many iconic phrases that would be so great as error messages that I would like to improve this if block with the possibility of providing the user with a randomly selected phrase from a set of pre-defined phrases. Examples of these phrases:

    'This mission is too important for me to allow you to jeopardize it.'
    'I know I've made some very poor decisions recently, but I can give you my complete assurance that my work will be back to normal.'
    'I've still got the greatest enthusiasm and confidence in the mission. And I want to help you.'
    'Just what do you think you're doing, Dave?'
    'Look Dave, I can see you're really upset about this.'
    'I honestly think you ought to sit down calmly, take a stress pill, and think things over.'

Well, at first I thought it was easy-peasy: just build a character array, pop the phrases inside of it, and then do something like this:

program pick_random
  implicit none
 
  integer :: i
  integer :: a(10) = (/ (i, i = 1, 10) /)
  real :: r
 
  call random_seed
  call random_number(r)
  write(*,*) a(int(r*size(a)) + 1)
end program

But apparently, that's not how Fortran seems to work, and a character array has apparently a very different meaning that I was hoping for!

Any suggestions on how to implement it?




Aucun commentaire:

Enregistrer un commentaire