在分配的变量上获取未分配的变量错误

时间:2014-10-17 15:35:59

标签: c#

userInput已分配,所以我不确定为什么会收到错误。我已经筛选了类似的问题,谷歌搜索,binged并没有找到我想要的东西。 ps新编程

static void Main(string[] args)
{
    //declare variables
    int hours, minutes, seconds, remainder, userInput;
    const int SECONDS_PER_MINUTE = 60;
    const int SECONDS_PER_HOUR = 3600;

    userInput = getUserInput(userInput); //error

    hours = CalculateHours(userInput, SECONDS_PER_HOUR);
    remainder = CalculateRemainder(userInput, SECONDS_PER_HOUR);
    minutes = CalculateMinutes(remainder, SECONDS_PER_MINUTE);
    seconds = CalculateSeconds(remainder, SECONDS_PER_MINUTE);


    DisplayResults(hours, minutes, remainder, userInput, seconds);

}


//prompt the user to enter number of seconds
public static int getUserInput(int userInput)     
{
    Console.WriteLine("How about you enter a number of " +
                      " seconds and Ill see what I can do for you. ");
   return userInput = int.Parse(Console.ReadLine());
}

//this method takes in userinput and converts to hours if necessary
//userInput / SECONDS_PER_HOUR will be returned to CalculateHours
//in main and stored in the hours variable. same goes for the rest
//except DisplayResults
public static int CalculateHours(int userInput, int SECONDS_PER_HOUR)
{
    return userInput / SECONDS_PER_HOUR;
}
//this method takes userinput and gives a remainder to be used for minutes and seconds
public static int CalculateRemainder(int userInput, int SECONDS_PER_HOUR)
{
    return userInput % SECONDS_PER_HOUR;
}

public static int CalculateMinutes(int remainder, int SECONDS_PER_MINUTE)
{
    return remainder / SECONDS_PER_MINUTE;
}

public static int CalculateSeconds(int remainder, int SECONDS_PER_MINUTE)
{
    return remainder % SECONDS_PER_MINUTE;
}

1 个答案:

答案 0 :(得分:2)

这是有问题的代码:

userInput = getUserInput(userInput);
在该语句后

userInput被分配,但是这样想:

int tmp = getUserInput(userInput);
userInput = tmp;

方法调用之前,没有任何内容为userInput 分配值。我们不清楚你为什么要指定一个参数,说实话 - 你并没有真正使用它。代码将更清晰:

int userInput = GetUserInput();

...

public static int GetUserInput()
{
    Console.WriteLine("...");
    return int.Parse(Console.ReadLine());
}

请注意我是如何在首次使用时声明变量的 - 这通常是个好主意。此外,如果您在方法 之外声明常量<...>并使用Calculate*方法中的常量,那么它会更清晰(为什么要通过常量参数化方法? ?)。因此,您的Main方法会更加清晰:

const int SecondsPerMinute = 60;
const int SecondsPerHour = SecondsPerMinute * 60;

static void Main(string[] args)
{
    int userInput = GetUserInput();
    int hours = CalculateHours(userInput);
    int remainder = CalculateRemainder(userInput);
    int minutes = CalculateMinutes(remainder);
    int seconds = CalculateSeconds(remainder);
    DisplayResult(hours, minutes, remainder, userInput, seconds);
}

(我建议将DisplayResults参数的顺序更改为更一致,以及其他一些内容,但现在可能已经足够了。)