我正在尝试制作一个简单的程序,要求用户输入一个整数。一旦程序接收到输入并存储它,然后从 1 计数到输入整数并将计数总和相加。然后它以一种有意义的方式向用户显示结果,并提示他们是否要处理另一个号码。这个程序的重点是使用循环和多个类。我知道我非常接近所需的最终产品,但无法弄清楚为什么 AccumulateValue() 方法无法正常工作。它似乎没有进入我所做的条件 while 语句。如果有人能给我一些关于我的问题的见解,那就太好了!
这是我的代码:
累加器应用程序.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class AccumulatorApp
{
static void Main(string[] args)
{
string loopControl = "Y";
int sum;
int enteredValue;
DisplayTitle();
while (loopControl == "Y" || loopControl == "YES")
{
enteredValue = InputInteger(0);
Accumulator number = new Accumulator(enteredValue);
sum = number.AccumulateValues();
DisplayOutput(sum, enteredValue);
Console.Write("\tWould you like to process another number? \n\t\t<Y or N>: ");
loopControl = Console.ReadLine().ToUpper();
}
}
public static void DisplayTitle()
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine();
Console.WriteLine("\tProgramming Assignment 05 - Accumulator - Robert");
DrawLine();
}
public static int InputInteger(int enteredValue)
{
Console.Write("\tPlease enter a positive integer: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (enteredValue > 0)
{
return enteredValue;
}
else
{
Console.WriteLine("\tInvalid input. Please enter a POSITIVE integer: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
}
return enteredValue;
/*
Console.Write("Please enter a positive integer: ");
int enteredValue = Convert.ToInt32(Console.ReadLine());
return enteredValue;
* */
}
public static void DisplayOutput(int sum, int inputValue)
{
Console.WriteLine("\tThe inputed integer is: {0}", inputValue);
Console.WriteLine("\tThe sum of 1 through {0} = {1}", inputValue, sum);
DrawLine();
}
public static void DrawLine()
{
Console.WriteLine("\t______________________________________________________");
Console.WriteLine();
}
}
}
累加器.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Accumulator
{
int integerEntered;
public Accumulator()
{
}
public Accumulator(int integerEntered)
{
int enteredInteger = integerEntered;
}
public int AccumulateValues()
{
int accumulatedValue = 0;
int counterValue = 1;
while (counterValue <= integerEntered)
{
Console.WriteLine("\tPasses through loop = {0}", accumulatedValue);
accumulatedValue = accumulatedValue + counterValue;
counterValue = counterValue + 1;
}
return accumulatedValue;
}
}
}