|
I'm stil beginner in c#. and i have made a small program. here is Main Program :
class Program
{
public static void Main()
{
while (true)
{
Console.WriteLine("Welcome");
Console.WriteLine("1 to go to Data class");
Console.WriteLine("type q to exit");
string input = Console.ReadLine();
if (input == "1")
{
}
else if (input == "q")
{
break;
}
else
{
Console.WriteLine("invalid option");
}
}
}
}
And this One is the Data Class.
class Data
{
public Data()
{
while (true)
{
Console.WriteLine("Choose Option : ");
Console.WriteLine("Press 1 to add and Press 2 To Go to Main Program");
int entry = int.Parse(Console.ReadLine());
if (entry == 1)
{
Console.WriteLine("Enter any number ");
int input = int.Parse(Console.ReadLine());
int result = input += 3;
Console.WriteLine("result");
Console.WriteLine(result);
}
else if (entry == 2)
{
}
else
{
Console.WriteLine("Invalid OPtion");
}
break;
}
}
}
And I want to do is . When the user type 2 in data class. then the program should go to main program, but unfortunately I dont know how to do that. Anyone Help please
|
|
|
|
|
Basically, don't.
Look at your code for the Data constructor (I'll rip out some of it top make it clearer):
while (true)
{
...
if (entry == 1)
{
...
}
else if (entry == 2)
{
}
else
{
...
}
break;
} Which means that regardless of what path you take though the if, you will always exit your loop at the end of the first iteration. So why is the loop there at all?
But there are more fundamental things: why are you getting the values inside the class constructor at all? That "locks" the class to always only work from the Console, you can't create an instance from data he entered last time if you save it. That's bad design - there is no good reasond for the Data class to have any idea where the data comes from. In fact is much, much better from an OOPs standpoint if the class has no idea where data comes from!
But your Data class is not a "real" class - it's just code you will call from your main method by a silly mechanism.
Classes aren't there to act as "super containers" for blocks of procedural code - they are supposed to be there to contain the data and it's related methods so each instance can work on it's own data.
For example, a simple class:
public class User
{
private string name;
private string hairColour;
private DateTime dateOfBirth;
public User(string name, string hairColour, int year, int month, int day)
{
this.name = name;
this.hairColour = hairColour;
dateOfBirth = new DateTime(year, month, day);
}
public int GetAge()
{
DateTime start = dateOfBirth;
DateTime end = DateTime.Now.Date;
int days = end.Day - start.Day;
if (days < 0)
{
end = end.AddMonths(-1);
days += DateTime.DaysInMonth(end.Year, end.Month);
}
int months = end.Month - start.Month;
if (months < 0)
{
end = end.AddYears(-1);
months += 12;
}
int years = end.Year - start.Year;
return years;
}
public string GetDetails()
{
return string.Format("{0} ({1}) is now {2}", name, hairColour, GetAge());
}
}
You create users thus:
User mike = new User("Mike Smith", "Blonde", 1990, 11, 14);
User joe = new User("Joe Ninety", "Mousey", 1983, 2, 1); And the class then handles all the work itself:
User mike = new User("Mike Smith", "Blonde", 1990, 11, 14);
User joe = new User("Joe Ninety", "Mousey", 1983, 2, 1);
Console.WriteLine(mike.GetDetails());
Console.WriteLine(joe.GetDetails());
And it will print:
Mike Smith (Blonde) is now 25
Joe Ninety (Mousey) is now 33
The User class is independent of the input and output mechanism, it just handles users and their data.
Do you see the difference between that and what you are trying to do?
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I have a treat for you
public static class AgeCalculationExtension
{
public static int CalculateCurrentAge(this DateTime birthday)
{
return CalculateAgeAsOf(birthday, DateTime.Today);
}
public static int CalculateAgeAsOf(this DateTime birthday, DateTime appointedDate)
{
if (appointedDate < birthday)
throw new ArgumentOutOfRangeException(nameof(appointedDate));
int age = appointedDate.Year - birthday.Year;
if (birthday > appointedDate.AddYears(-age))
age--;
return age;
}
}
edit: Added input validation.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
modified 27-Apr-16 7:48am.
|
|
|
|
|
Ooh goody. Here's an input for it:
DateTime dateTime = new DateTime(1968, 2, 29);
int age = dateTime.CalculateAgeAsOf(new DateTime(1964, 2, 29)); Apparently, that person is -4.
This space for rent
|
|
|
|
|
Totally correct answer.
You have the birthday in 1968, and are asking age as of 1964.
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
While it's syntactically correct, it's also logically bogus. It's why public inputs should always be checked.
This space for rent
|
|
|
|
|
I agree - and added it.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Sascha Lefèvre wrote: if (birthday == null) ...
if (appointedDate == null) ...
A DateTime can never be null .
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks, Richard - it was a bit too late yesterday.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
I have my custom error handler defined in Global.asax:
void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if(httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch(Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
Im trying to test my error handler by raising an error like this in my service model:
if(albums != null)
{
albums = null;
ctx.SpotifyAlbums.AddRange(albums);
ctx.SaveChanges();
}
This raises an exception, but how can I "catch" this exception with my custom error handler?
|
|
|
|
|
Member 12045692 wrote: This raises an exception, but how can I "catch" this exception with my custom error handler? According to MSDN[^];
An error handler that is defined in the Global.asax file will only catch errors that occur during processing of requests by the ASP.NET runtime. For example, it will catch the error if a user requests an .aspx file that does not occur in your application. However, it does not catch the error if a user requests a nonexistent .htm file. For non-ASP.NET errors, you can create a custom handler in Internet Information Services (IIS). The custom handler will also not be called for server-level errors.
You may want to play around with the Complete Example for Error Handlers[^].
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Create a menu
1.Register Student
2.View Student details");
3.Check student balance");
4.Pay fees");
5.Exit"
1. when you click on register student the program should prompt you for name,surname,date of birth,gender,student number,
2. when you click on view student details it should allow you to retrieve information in 1......search by student number or name
3. allow you to chk student balance....search student number or name.....
4. allow you to deducted from a constant double variable 200000
store all details in a file.
it should be able to store 400 students
this is what i tried out.......
........................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string info;
int code;
const double totalcost=20000;
double amount_owed;
string Firstname;
string Surname;
DateTime DOB;
char Gender;
double Total_Fees_paid;
string nTitle;
string nFirstname;
string nsurname;
DateTime nDOB;
string nOccupation;
string nDesgination;
int students;
Console.WriteLine("The Hogwarts Academy");
Console.WriteLine("---- ----------");
Console.WriteLine(" 1. Register Student");
Console.WriteLine(" 2. View Student details");
Console.WriteLine(" 3. Check student balance");
Console.WriteLine(" 4. Pay fees");
Console.WriteLine(" 5. Exit");
Console.WriteLine("---- ----------");
try
{
code = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("You enter the wrong character e.g abcd!@#");
Console.WriteLine("Please re-enter a number e.g 12345");
Console.Clear();
code = int.Parse(Console.ReadLine());
}
if (code > 5)
{
Console.WriteLine("The Hogwarts Academy");
Console.WriteLine("---- ----------");
Console.WriteLine(" 1. Register Student");
Console.WriteLine(" 2. View Student details");
Console.WriteLine(" 3. Check student balance");
Console.WriteLine(" 4. Pay fees");
Console.WriteLine(" 5. Exit");
Console.WriteLine("---- ----------");
Console.WriteLine("\n\nPlease re-enter a number which is on the code list");
code = int.Parse(Console.ReadLine());
}
else if (code == 1)
{
StreamWriter writer = new StreamWriter("Student.txt");
Console.WriteLine("Number of students");
students=int.Parse(Console.ReadLine());
for (int i = 0; i < students; i = i + 1)
{
Console.WriteLine("________________Student information______________");
Console.WriteLine("Enter student name ");
Firstname = Console.ReadLine();
Console.WriteLine("Enter the Surname ");
Surname = Console.ReadLine();
Console.WriteLine("Enter student date of birth");
DOB = DateTime.Parse(Console.ReadLine());
Console.WriteLine("Enter student Gender either F/M ");
Gender = char.Parse(Console.ReadLine());
Console.WriteLine("Total fees paid N$");
Total_Fees_paid = double.Parse(Console.ReadLine());
amount_owed = totalcost - Total_Fees_paid;
Console.WriteLine("__________NEXT OF KIN__________");
Console.WriteLine("Enter next of kin/parent/gurdian's Title ");
nTitle = Console.ReadLine();
Console.WriteLine("Enter next of kin/parent/gurdian's Name ");
nFirstname = Console.ReadLine();
Console.WriteLine("Enter next of kin/parent/gurdian's Surname ");
nsurname = Console.ReadLine();
Console.WriteLine("Enter next of kin/parent/gurdian's date of birth");
nDOB = DateTime.Parse(Console.ReadLine());
Console.WriteLine("Enter next of kin/parent/gurdian's Occupation");
nOccupation = Console.ReadLine();
Console.WriteLine("Enter next of kin/parent/gurdian's Desgnation");
nDesgination = Console.ReadLine();
//StreamWriter SW; //new StreamWriter("@info.txt");
//SW = File.AppendText(Firstname + Surname + DOB + Gender + Total_Fees_paid + amount_owed + "Next of kin" + nTitle + nFirstname + nsurname + nDOB + nOccupation + nDesgination + ".txt");
//SW.Close();
}
}
else if (code == 2)
{
}
}
}
}
|
|
|
|
|
|
Member 12485384 wrote: when you click on register student This does not make it sound like a console-app.
The specs do not state what kind of file. If you're allowed to use a database, then you would not have to write code to update the file and rewrite all contents. If you're not allowed to use a database, then a format like XML or JSON would be preferred, as they are easier to store relational data than simple text-files.
That would be simply based on the code that I'm looking at; you said that this is what you tried, but not if it actually performs the required tasks, whether it works or not, or where you are stuck (if you are).
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
you will only understand if i send you the official pdf.....
|
|
|
|
|
Can't you copy/paste the relevant parts into a forum-post?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
First of all, when you post code here on Code Project, please use the correct markup so it is legible. That means using the code button along the top edge of the Message editor.
Next, instead of just giving a "code dump", tell us exactly what isn't working as you expect and post only the relevant code.
This is clearly homework, so don't expect to receive code; but you'll probably be given advice and suggestions to help you learn!
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
How to get a balance code ???!!
|
|
|
|
|
|
CAN YOU GIVE A FULL CODE???
ITS IN-COMPLETE
|
|
|
|
|
hi
I tried to write code that implicitly convert a generic type to another but it failed with interface. With subclass it worked, i thought it should be the other way.
public class ConvertibleClass<T>
{
T holder;
public ConvertibleClass(T obj)
{
holder = obj;
}
public static implicit operator ConvertibleClass<T>(T obj)
{
return new ConvertibleClass<T>(obj);
}
public static implicit operator T(ConvertibleClass<T> obj)
{
return obj.holder;
}
}
public interface IGenericInterface<T>
{
}
public class GenericClass : IGenericInterface<AnyClass>
{
public GenericClass(int id)
{
ID = id;
}
public int ID { get; set; }
}
public class AnyClass
{ }
In this code i need any class that implements 'IGenericInterface<T>' to be converted to 'Convertible' class and vice versa.
But!!
public void DoSomthing(IGenericInterface<AnyClass> doSomthingWithThis)
{
List<ConvertibleClass<IGenericInterface<AnyClass>>> ListOfMedies = new List<ConvertibleClass<IGenericInterface<AnyClass>>>();
ConvertibleClass<IGenericInterface<AnyClass>> item = new GenericClass(4);
ListOfMedies.Add(new GenericClass(1));
ListOfMedies.Add(item);
ListOfMedies.Add(new GenericClass(2));
item = doSomthingWithThis;
ListOfMedies.Contains(doSomthingWithThis);
ListOfMedies.Add(doSomthingWithThis);
}
And code for calling the method
DoSomthing(new GenericClass(4));
I cant figure it out. HELP!
And THX
|
|
|
|
|
The generic interface is a red-herring. Your code will fail even with a non-generic interface, because the C# specification explicitly forbids it:
A class or struct is permitted to declare a conversion from a source type S to a target type T provided all of the following are true:
- S and T are different types.
- Either S or T is the class or struct type in which the operator declaration takes place.
- Neither S nor T is object or an interface-type.
- T is not a base class of S, and S is not a base class of T.
...
User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.
Eric Lippert posted a great explanation for this restriction on StackOverflow:
More on implicit conversion operators and interfaces in C# (again) - Stack Overflow[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thanks alot, so i should find another way.
|
|
|
|
|
GOOD BY
modified 26-Apr-16 11:17am.
|
|
|
|
|
So you have one user, and his username is "textUsername.Text", and an SQL system that doesn't mind errors?
Look at your code:
SqlDataAdapter sda = new SqlDataAdapter("select count(*) from Login Whare Username = textUsername.Text ; Password = textPassword.Text; +", conn);
DataTable dt = new System.Data.DataTable(); Dump some of it to make it more obvious:
string s = "select count(*) from Login Whare Username = textUsername.Text ; Password = textPassword.Text; +"; And you have "just" the SQL you are getting the server to execute.
1) WHERE is spelled with an 'E', not an 'A':
from Login Whare Username
2) This inserts the name of your controls into the command, rather than the contents the user entered. Even if you fix the WHARE problem, it won't work.
3) Semicolon is a statement terminator in SQL, not an item separator:
Whare Username = textUsername.Text ; Password = textPassword.Text
Probably you wanted to say AND instead of ';'
4) What does '+' do as an SQL command? Nothing - it will be an unexpected character.
5) Even if it did work, never store passwords in clear text! It is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^] Also see here: Code Crime 1[^]
6) Don't hard code connection strings: They should be in settings files, not in the code.
7) Attaching a DB file is a bad, bad idea. It starts a new instance of your local DB server and will only work with Local SQL Express installations - it's also very much inefficient.
Make the DB a part of SQL by creating it in SQL and let it manage it.
8) SQL Connections and so forth are a scarce resource - and you are responsible for clearing up after yourself. Always Dispose of them when you are finished with them.
9) Fix all that, and your code is going to be vulnerable to SQL Injection. Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
Follow the link at (5) and you will see much better code to do all this.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|