How do I save information reached through a method to a variable?

184 Views Asked by At

I am making a program to calculate someone's GPA based user input. For one of the methods I am writing, I ask the user to enter a letter grade. I then convert the letter to the corresponding GPA. How do I save this GPA to a variable? Would I save it as a variable when I call the method in the program or in the method itself?

public static double GetGradePoint(string LetterGrade)
 {
    Console.WriteLine("Enter your letter grade for each class");
    string letter = Console.ReadLine();
    if (letter == "A")
    {
        return 4;
    }
    if (letter == "A-")
    {
        return 3.7;
    }
    if (letter == "B+")
    {
        return 3.3;
    }
    if (letter == "B")
    {
        return 3;
    }
    if (letter == "B-")
    {
        return 2.7;
    }
    if (letter == "C+")
    {
        return 2.3;
    }
    if (letter == "C")
    {
        return 2;
    }
    if (letter == "C-")
    {
        return 1.7;
    }
    if (letter == "D+")
    {
        return 1.3;
    }
    if (letter == "D")
    {
        return 1;
    }
    if (letter == "F")
    {
        return 0;
    }
}
1

There are 1 best solutions below

0
Mosia Thabo On

You could try two different things:

Approach One (Not Recommended)

Use this approach if you will only be using your input data once and won't require to use it anywhere else in your logic. Take not of the parameters. You do not need to declare a parameter on this case

public static double GetGradePoint()
 {

    Console.WriteLine("Enter your letter grade for each class");
    string letter = Console.ReadLine();

    //... your if statements/ switch statement here
    if (letter == "A")
    {
        return 4;
    }
    //...
}

Then inside your main()

double Grade = GetGradePoint();

Approach Two (Recommended)

Use this approach and treat your GetGradePoint as a pure function that takes a parameter and return a result. Take note of the parameter.

public static double GetGradePoint(string LetterGrade)
 {
    //... your if statements/ switch statement here
    if (LetterGrade== "A")
    {
        return 4;
    }
    //...
}

Then inside your main()

Console.WriteLine("Enter your letter grade for each class");
string letter = Console.ReadLine();

//pass letter as parameter to get the GradePoint
double Grade = GetGradePoint(letter);

Note: Always try to treat your methods as pure functions. functions that receive information via parameters and return computed result.