After running the program I can only insert data for the first student, and after that it only displays what I should insert, but does not give me the right to do so. No compile errors. Although I think that the problem is when I assign the variables, it might be an issue there, because I don't know if I should initialise the int with 0 or not. I obtain a lot of compiling error if I don't initialise the variables. Also, why does it display the Student phone number with a random number, "48" in my case?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomCollections
{
internal class Program
{
string studentNumber;
string studentName;
string age;
int phoneNumber;
public static void enterData()
{
int studentNumber, age, phoneNumber;
string studentName;
Console.WriteLine("Enter Student Number:");
studentNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Name:");
studentName = Console.ReadLine();
Console.WriteLine("Enter Age:");
age = int.Parse(Console.ReadLine());
Console.WriteLine("Enter phone number:");
phoneNumber = int.Parse(Console.ReadLine());
}
public static void displayData()
{
string studentNumber=null;
string studentName=null;
string age=null;
int phoneNumber=0;
Console.WriteLine("Student Number:{0}",studentNumber);
Console.WriteLine("Student Name:{0}",studentName);
Console.WriteLine("Student Age:{0}", age);
Console.WriteLine("Student phone number:{0}",phoneNumber);
Console.ReadKey();
}
public static void Main(String[] args)
{
string studentNumber;
string studentName;
string age;
int phoneNumber;
enterData();
displayData();
}
}
}
I will also display the result here:
Enter Student Number:
2
Enter Name:
seli
Enter Age:
22
Enter phone number:
2207885
Student Number:
Student Name:
Student Age:
Student phone number:48
You have variables named
studentNumber,studentName,age, andphoneNumberdefined in four different places. Local variables with the same name in different methods do not represent the same storage. In order for the values read byenterData()to be accessible todisplayData()you either need to pass them as parameters or store them in class-level, not local, variables; the latter will require the least changes to your code.After making these changes...
staticmodifier to your fields so you can access them fromstaticmethods.studentNumberandagefields fromstringtointsince you are parsing them toint.studentNumber,studentName,age, andphoneNumbervariables from theenterData(),displayData(), andMain()methods....that results in this code...
...which worked as-expected for me.