Sunday 15 August 2010

c# - How do I rewrite this code to accept user input? -



c# - How do I rewrite this code to accept user input? -

i have next code prints area of right triangle. can see dimensions of triangles hard coded program. wish user input values x , y. how go changing below programme user prompted come in these values?

public class triangle { private int height, length; public triangle(int x, int y) { length = x; height = y; } public double triarea() { double area; area = 0.5 *(height * length); homecoming area; } } class trianglearea { public static void main() { triangle tri1 = new triangle(15, 10); console.writeline("area 1=" + tri1.triarea()); triangle mytriangle = new triangle(12, 5); console.writeline("my triangle area =" + mytriangle.triarea()); console.readline(); } } }

a naïve approach following.

console.writeline("add integer x: "); int x = convert.toint32(console.readline()); console.writeline("add integer y: "); int y = convert.toint32(console.readline()); triangle tri1 = new triangle(x, y); console.writeline("area 1=" + tri1.triarea());

a more robust approach validate user input , have input loop user can calculate area of more 1 triangle. following:

static void main(string[] args) { bool keepprompting = true; while (keepprompting) { bool wehavevalidxvalue = false; int x = 0, y = 0; while (!wehavevalidxvalue) { console.writeline("enter value x , press return:"); string xvalue = console.readline(); wehavevalidxvalue = int.tryparse(xvalue, out x); if (!wehavevalidxvalue || x <= 0) { wehavevalidxvalue = false; console.writeline("invalid value"); } } bool wehavevalidyvalue = false; while (!wehavevalidyvalue) { console.writeline("enter value y , press return:"); string yvalue = console.readline(); wehavevalidyvalue = int.tryparse(yvalue, out y); if(!wehavevalidyvalue || y <= 0) { wehavevalidyvalue = false; console.writeline("invalid value"); } } triangle mytriangle = new triangle(x, y); console.writeline("my triangle area = {0}", mytriangle.triarea()); console.writeline("continue? (y/n)"); string response = console.readline(); if(response.equals("n", stringcomparison.invariantcultureignorecase)) { keepprompting = false; } } }

c#

No comments:

Post a Comment