问题描述
我正在使用Rob Miles编写的C#编程黄皮书学习C#。他正在讨论一个计算器示例,该计算器用于确定所需的总玻璃面积(以平方米为单位)。我重新创建了这段代码,并想通过对我有意义的事情来尝试对其进行改进。例如,在他的代码中,他使用了很多空白行,这些行对我来说似乎并不有吸引力。我想尝试使其看起来更干净。我主要想消除第一行空白行,但是确保空白行会出现在下一行。
这是原始代码。
double width,height,woodLength,glassArea;
const double MAX_WIDTH = 5.0;
const double MIN_WIDTH = 0.5;
const double MAX_HEIGHT = 3.0;
const double MIN_HEIGHT = 0.75;
string widthString,heightString;
do {
Console.Write("\nGive the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + ": ");
widthString = Console.ReadLine();
width = double.Parse(widthString);
if (width < MIN_WIDTH){
Console.WriteLine("Width is too small.");
}
if (width > MAX_WIDTH){
Console.WriteLine("Width is too large.");
}
} while (width < MIN_WIDTH || width > MAX_WIDTH);
我尝试使用goto,但是由于循环是另一种方法(?),因此无法正常工作。通过一些谷歌搜索,我发现goto是非常糟糕的做法,但是我无法想到要使用的任何其他方法。 (我也不知道)
Console.Write("Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + ": ");
goto first_loop;
do {
Console.Write("\nGive the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + ": ");
first_loop:
widthString = Console.ReadLine();
width = double.Parse(widthString);
if (width < MIN_WIDTH){
Console.WriteLine("Width is too small.");
}
if (width > MAX_WIDTH){
Console.WriteLine("Width is too large.");
}
} while (width < MIN_WIDTH || width > MAX_WIDTH);
解决方法
我主要是想消除第一个空白行,但是请确保 空白行将出现在下一行。
从提示中删除\n
,而是将其添加到两个错误消息的末尾:
do
{
Console.Write("Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + ": ");
widthString = Console.ReadLine();
width = double.Parse(widthString);
if (width < MIN_WIDTH)
{
Console.WriteLine("Width is too small.\n");
}
else if (width > MAX_WIDTH)
{
Console.WriteLine("Width is too large.\n");
}
} while (width < MIN_WIDTH || width > MAX_WIDTH);
但是,如果我自己写这个,我将使用一个布尔值来表示整体成功,并在while循环中检查是否有条件。我也将使用double.TryParse()
,如下所示:
bool valid = false;
do
{
valid = true; // assume good until proven otherwise
Console.Write("Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + ": ");
widthString = Console.ReadLine();
if (double.TryParse(widthString,out width))
{
if (width < MIN_WIDTH || width >MAX_WIDTH )
{
valid = false;
Console.WriteLine("Width is too " + ((width<MIN_WIDTH) ? "small" : "large") + ".");
}
}
else
{
Console.WriteLine("Invalid width entry. Please try again.");
valid = false;
}
if (!valid)
{
Console.WriteLine();
}
} while (!valid);
,
如果您也不想像@Idle_Mind的解决方案那样在末尾添加其他空行,则可以执行以下操作
for(i = 1; i <= 100; i++) {
double r = Math.random();
double in = r * 100;
System.out.print(in + ",");
}