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

本文关键字:分配 变量 错误 获取 | 更新日期: 2023-09-27 18:26:51

userInput,所以我不确定为什么会出错。我已经筛选了类似的问题,在谷歌上搜索,大吃大喝,但没有找到我想要的东西。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;
}

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

以下是有问题的代码:

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参数的顺序,使其更加一致,还有一些其他内容,但目前可能已经足够了。)