I am writing a program that allows the user to choose an option 1 or 2.
If they choose option 3 the console is supposed to say to choose only options 1 or 2 and return to the top of the loop but it just exits.
If I put break or continue it loops forever.
I cannot figure out how to get back to the top.
Thank you for your help.
This is my program:
import math, strutils
stdout.write "nt1) SQUAREnt2) TRIANGLEnn"
stdout.write "CHOICE: "
var Choice : int = 0 Choice = parseInt(stdin.readLine)
while true:
- if Choice == 1:
- echo "Enter the length of one of the square's sides: " stdout.write "Length: " var Square : int = parseInt(stdin.readLine) var AreaOfSquare = Square ^ 2
echo "Area: ", AreaOfSquare quit(0)
- elif Choice == 2:
- echo "Enter the base and height of the triangle: " stdout.write "Base: " var Base : int = parseInt(stdin.readLine) stdout.write "Height: " var Height : int = parseInt(stdin.readLine)
var AreaOfTriangle = Base * Height div 2 echo "Area: ", AreaOfTriangle quit(0)
else:
echo "nnERROR: CHOOSE ONLY OPTIONS 1 OR 2!"
Please, when you post - format your code with code blocks: https://forum.nim-lang.org/about/rst
For example:
```nim
echo hello world
```If they choose option 3 the console is supposed to say to choose only options 1 or 2 and return to the top of the loop but it just exits.
The part that asks for the user's choice needs to be inside the loop. That way, when the loop goes back to the top, it asks for a new choice instead of reusing the old one:
import math, strutils
while true:
# DISPLAY THE MESSAGE:
# 1) SQUARE
# 2) TRIANGLE
stdout.write "\n\t1) SQUARE\n\t2) TRIANGLE\n\n"
# IF THE USER ENTERS 1, ASK THE USER FOR THE LENGTH OF ONE OF THE SIDES OF THE SQUARE.
stdout.write "CHOICE: "
var Choice : int = 0
Choice = parseInt(stdin.readLine)
if Choice == 1:
echo "Enter the length of one of the square's sides: "
stdout.write "Length: "
var Square : int = parseInt(stdin.readLine)
var AreaOfSquare = Square ^ 2
# DISPLAY THE AREA.
echo "Area: ", AreaOfSquare
quit(0)
# IF THE USER ENTERS 2, ASK FOR THE BASE AND THE HEIGHT OF THE TRIANGLE.
elif Choice == 2:
echo "Enter the base and height of the triangle: "
stdout.write "Base: "
var Base : int = parseInt(stdin.readLine)
stdout.write "Height: "
var Height : int = parseInt(stdin.readLine)
# DISPLAY THE AREA.
var AreaOfTriangle = Base * Height div 2
echo "Area: ", AreaOfTriangle
quit(0)
# IF THE USER TYPES ANYTHING OTHER THAN 1 OR 2, DISPLAY AN ERROR MESSAGE.
else:
echo "\n\nERROR: CHOOSE ONLY OPTIONS 1 OR 2!" Welcome to Nim! Please read the docs. They're fairly well done, and mostly complete. There is a remarkably handy table of contents on the left side.
https://nim-lang.org/docs/manual.html#statements-and-expressions-while-statement