Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: my program will not display a correct answer, to a random question?

by ig (Vicar)
on Aug 05, 2011 at 09:08 UTC ( #918707=note: print w/ replies, xml ) Need Help??


in reply to my program will not display a correct answer, to a random question?

I find it helpful to write programs that handle all possible input, processing expected input as required and giving error messages when unexpected input is received. In your case, you might have written your program as follows:

use strict; use warnings; print "Type in a number: "; my $x = <>; chomp($x); die "ERROR: '$x' is not a number" unless($x =~ /^\d+$/); print "Type in another number: "; my $y = <>; chomp($y); die "ERROR: '$y' is not a number" unless($y =~ /^\d+$/); print "What would you like done?\n\nYour choice is:\n1) Add\n2) Subtra +ct\n3) Multiply\n4) Divide\n"; my $ask = <>; chomp($ask); if ($ask eq "Add") { my $z = $x + $y; print "$x + $y = $z"; } else { die "ERROR: '$ask' is an unknown operation"; }

With the input you show in your post, this program gives:

Type in a number: 4 Type in another number: 5 What would you like done? Your choice is: 1) Add 2) Subtract 3) Multiply 4) Divide 1 ERROR: '1' is an unknown operation at ./test.pl line 23, <> line 3.

This may not be the "correct answer", but it may help you understand what is wrong.


Comment on Re: my program will not display a correct answer, to a random question?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://918707]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2015-07-05 10:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls