-1

I need help! the output should be prompted to enter student name and their GPA in CreateStudentList() method like how I typed it out. But the output only shows this Student List1 GPAs: Student List2 GPAs:

What am I doing wrong? Is it the way I called the createstudentlist() method?

class Student
{
    public string strName;
    public float fltGPA;

    public Student(string n, float gpa)
    {
        strName = n;
        fltGPA = gpa;
    }
}
class Program
{
    static void DisplayStudentList(List<Student> slist)
    {
        foreach(Student s in slist)
        {
            Console.WriteLine("{0}", s.fltGPA);
        }
    }
    static List<Student> CreateStudentList()
    {
        List<Student> studentlist = new List<Student>();
        Student objStudent;

        string r = "";
        while (r == "Y")
        {
            Console.Write("Enter name:");
            string n = Console.ReadLine();
            Console.WriteLine("Enter GPA:");
            float g = float.Parse(Console.ReadLine());

            objStudent = new Student(n, g);
            studentlist.Add(objStudent);

            Console.Write("Do you want to continue? (Y/N): ");
            r = Console.ReadLine();
        }
        return studentlist;
        
    }
    static void Main(string[] args)
    {
        List<Student> studentList1 =  CreateStudentList();
        List<Student> studentList2 = CreateStudentList();
        
        Console.WriteLine("Student List1 GPAs:");
        DisplayStudentList(studentList1);
        Console.WriteLine("Student List2 GPAs:");
        DisplayStudentList(studentList2);

        foreach (Student gpa1 in studentList1)
        {
            foreach (Student gpa2 in studentList2)
            {
                if (gpa1.fltGPA == gpa2.fltGPA)
                {
                    Console.WriteLine("Students with same GPA: \n {0} \n {1}",
                        gpa1.strName, gpa2.strName);
                }
            }
        }

        Console.ReadKey();
    }
}

}

  • 1
    `string r = ""; while (r == "Y")` its never `Y` at first, so it doesnt enter into the loop. Have you set breakpoints and stepped through your code? – Trevor Nov 26 '21 at 06:07

1 Answers1

1

You have

string r = "";
while (r == "Y") 
{ ... 

The while loop will never be entered. Either set r = "Y" or use a do/while loop.

Another thing to consider:

if (gpa1.fltGPA == gpa2.fltGPA)

compares floats by equality. You should use a comparison with epsilon

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • Ahhh okay i get it now! so sorry i just started learning arrays for C# and was confused with how it works.. thank you so much! – Beginnercoder Nov 26 '21 at 06:19