Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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 ./ line 23, <> line 3.

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://918707]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2018-03-22 01:16 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (272 votes). Check out past polls.