我想做一个简单的程序,要求用户输入一个整数。一旦程序收到它所需要的输入并将其存储起来,然后从1开始对输入整数进行计数,并将计数总和相加。然后以有意义的方式向用户显示结果,并在他们想要处理另一个号码时提示他们。这个程序的重点是使用循环和多个类。我知道我非常接近期望的最终产品,但无法弄清楚为什么AccumulateValue()方法无法正常工作。它似乎没有进入我作出的有条件的声明。如果有人能给我一些见解,那我的问题就会很棒!使用多个类
这里是我的代码:
AccumulatorApp.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();
}
}
}
Accumulator.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;
}
}
}
正如你可能摆脱数据成员integerEntered的说明和你的价值构造(保存价值,这是在价值构造的通话结束时失去了局部变量)。为了给你的值构造函数更多的含义,你应该将传递给它的参数保存到数据库中。在这种情况下,这应该是完全合法的: public Accumulator(int integerEntered) { integerEntered = integerEntered; } – Teeknow