Need Help With a Simple C# Program! - c#

I Want to call a class into the Main method.. And I'm getting this error :s
Code:
using System;
namespace AddMinusDivideMultiply
{
class Program
{
public static int i, j;
public static void Main()
{
Console.Write("Please Enter The First Number :");
string temp = Console.ReadLine();
i = Int32.Parse(temp);
Console.Write("Please Enter The Second Number :");
temp = Console.ReadLine();
j = Int32.Parse(temp);
Minuz.minus(); // Here its generating an Error - Error 1 The name 'Minuz' does not exist in the current context
}
}
class Terms
{
public static void Add()
{
int add;
add = Program.i + Program.j;
Console.WriteLine("The Addition Of The First and The Second Number is {0}", add);
}
class Minuz
{
public static void Minus()
{
int minus;
minus = Program.i - Program.j;
Console.WriteLine("The Subraction Of The First and The Second Number is {0}", minus);
}
}
}
}

Case matters in C#!
Call this:
Minuz.Minus();
Also, need to change your braces so it's not inside Terms:
class Terms
{
public static void Add()
{
int add;
add = Program.i + Program.j;
Console.WriteLine("The Addition Of The First and The Second Number is {0}", add);
}
}
class Minuz
{
public static void Minus()
{
int minus;
minus = Program.i - Program.j;
Console.WriteLine("The Subraction Of The First and The Second Number is {0}", minus);
}
}

That's because the Class Minuz is defined inside the Class Terms so it really is not defined in the context you are trying to use it.
You did not close the definition of Terms before declaring Minuz

The problem is that the class Minuz is declared inside the class Terms, and it is private. This means that it is not visible from the Main method.
There are two possible ways to solve it:
Make the class Minuz internal or public and chance the call to the Minus method to Terms.Minuz.Minus()
Move the declaration of the class Minuz out from the Terms class so that it is instead declared in the namespace.
Also, as pointed out by others; mind the case of the method name. That will be your next problem once the class visibility has been fixed.

You have embedded the Minuz class inside the Terms class. If you make it public class Minuz you can call
Terms.Minuz.Minus();
to solve the error. But you probably want to move the Minuz class out of Terms.

Unless its a typo, you're missing a closing bracket for the Terms class. The way its currently written in your post, you would need to put this statement in your Main method:
Terms.Minuz.Minus();

Related

C# - understanding Objects, Classes, and Method interactions

Very, very new programmer here facing some big troubles, I am trying to achieve as follows:
I want to write a very basic program in which the user is prompted to input two double variables, I then want the program to call separate methods, that will perform mathematical operations on those two variables and provide the user the answers.
Example of desired output:
Input First Number
x
Input Second Number
y
Add: z
Subtract: z
My aim in this is to practice using objects, but I am having issues, see this snippet as an example.
class Variables
{
public string First { get; set; }
public string Second { get; set; }
}
class Program
{
Variables inputs = new Variables()
{
Console.WriteLine("Please input first number"),
First = Console.ReadLine(),
Console.WriteLine("Please input second number"),
Second = Console.ReadLine(),
};
static void Main(string[] args)
{
Addthem();
}
public string Addthem()
{
double answer = Convert.ToDouble(inputs.First) + Convert.ToDouble(inputs.Second);
return ("Added: " + answer);
}
}
When trying to call Addthem, I have no 'object reference',
in my object 'inputs', I cannot print to console to prompt user input?
And finally (most mind bogglingly to me), my Main method is not suitable as an entry point for the program, this is what I am MOST clueless on.
Am I even on the right track? As I said very novice so sorry for egregious errors or general ignorance, I am just trying to better understand what I am not seeing in the interactions between Classes, Objects, Methods.
You've got all the ingredients right, but they need to be rearranged to make a good cake. Main() is the entry point, so anything you want to do has to be inside Main() or be called by something inside Main().
A useful concept to know is the difference between a class and an object.
A class is just a specification which says you can have these properties and methods, but you need to create an instance of the class first.
An object is an "instance" of a class and you can call the class methods (functions) through that object. Eg inputs is an instance of the Variables class.
using System;
class Variables
{
public string First { get; set; }
public string Second { get; set; }
public string AddthemInClass()
{
double answer = Convert.ToDouble(First) + Convert.ToDouble(Second);
return ("Added: " + answer);
}
}
class Program
{
static void Main(string[] args)
{
// You had the code to initialise `inputs` outside of Main(),
// so it wouldn't get executed
// It needs to be inside Main()
// `inputs` is created as an instance of the `Variables` class
Variables inputs = new Variables();
Console.WriteLine("Please input first number");
inputs.First = Console.ReadLine();
Console.WriteLine("Please input second number");
inputs.Second = Console.ReadLine();
// You need to tell Addthem() what to work on, ie, pass in `inputs`
var result = Addthem(inputs);
Console.WriteLine( result );
// Or, you could call AddthemInClass through the `inputs` object
// because AddthemInClass is a method of Variables class
var result2 = inputs.AddthemInClass();
Console.WriteLine( result2 );
}
// This should be a static method. If you don't do this, you need to have it
// in a class and call it through an instance of that class
// You could put it inside Variables class - see AddThemInClass()
public static string Addthem(Variables inputs)
{
double answer = Convert.ToDouble(inputs.First) + Convert.ToDouble(inputs.Second);
return ("Added: " + answer);
}
}

Using functions in c#

I am struggling to understand how functions work outside of main. I simply need to compute a total using information that is put in by the user in main, but I am supposed to call on a function to total this up. Here is the code I have so far, I am sure it is not very close to right, a nudge in the right direction would be a huge help
namespace ConsoleApplication17
{
class Program
{
static void Main(string[] args)
{
string customerName, customerState;
double numberItems, itemPrice;
Console.WriteLine("Please enter the customer name");
customerName = Console.ReadLine();
Console.WriteLine("Please enter the state in which you reside:");
customerState = Console.ReadLine();
Console.WriteLine("How many items were purchased?");
numberItems = int.Parse(Console.ReadLine());
Console.WriteLine("What was the price of said items?");
itemPrice = Convert.ToDouble(Console.ReadLine());
}
public static double ComputeTotal (double total)
{
double totalAmount;
Console.Write(total);
}
}
public static double ComputeTax (double totalAmount, string state, string fl, string nj, string ny)
{
if (state == fl)
return totalAmount*.06;
else if (state == nj)
return totalAmount*.07;
else if (state == ny)
return totalAmount*.04;
}
In short, I need to use the function ComputeTotal to multiply the numberItems and itemPrice
A function basically takes some data from you and returns (some other?) data to you.
In your case you want to give the function 2 pieces of data - qty and price, and you want it to return you the total price.
public static double ComputeTotal(double qty, double price)
{
return qty* price;
}
This function ComputeTotal accepts 2 variables of type double.
They are qty and price.
The function then multiplies these 2 variables and returns the result to the caller.
In your main method, this is how you use(call) the function.
static void Main(string[] args)
{
// rest of your code here
var total = ComputeTotal(numberItems, itemPrice);
Console.WriteLine(total);
}
Here I am creating a new variable called total, and I am assigning the return value of ComputeTotal function to this variable.
The ComputeTotal function requires 2 parameters and I am passing 2 variables that you created in your code. For brevity I have not typed any of your original code, and your code should be at the location of my comment "// rest of your code here" .
your method/function could be like this
public static double ComputeTotal (double itemPrice, int quantity)
{
return itemPrice * quantity
}
in your main method you can do like this
static void Main(string[] args)
{
double total_price=0.0;
total_price = ComputeTotal ( itemPrice, numberItems)
Console.WriteLine("totl price : {0}",total_price);
}
understand how functions work
I am distilling this significantly, but a function for this definition is really a method which returns a value. In C# there is no distinction between functions and methods for they are the same with differences being whether something returns data or operates on a referenced instance of a class instance.
The real difference is in the calling mechanism on whether one instantiates (calls new on a class); they are instantiatitng a class. For this assignment, your teacher does not want you to instantiate a class.
Hence you will call function(s) which are static methods that can be called by anyone without instantiating any classes.
With that in mind, your teacher wants you to learn a function type call so he /she wants you to create a static method off of the class Program which can be called by Main because it is static as well.
So create your function type static method that will return a value; hence it will mimic functions in other languages.
outside of main.
Now Main can have static methods, but so can other classes which can be called from within a Main's static method as well.
The other class like that looks like this...and is called by fully qualifying the location such as {ClassName}.{Static Method Name}.
class Program {
static void Main(...)
{
Console.WriteLine( TheOtherClass.AFunction() );
}
}
public class TheOtherClass
{
public static string AFunction()
{
return "A String From this Function. :-) ";
}
}
Note if TheOtherClass is in a different namespace, access it such as {Namespace}.{ClassName}.{Static Method Name}. But you should make sure that the other class is in the same Namespace as found in your current example of ConsoleApplication17.

Difficulty regarding passing constructor parameters

This is an assignment for a class.
Here is my code so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Proj03
{
class MyClass
{
public string MyClass(bool First, int Last)
{
if (First == true)
{
return "FirstName";
}
else if (Last == 3)
{
return "LastName";
}
}
}
class Program
{
static void Main(string[] args)
{
bool var1 = true;
int var2 = 3;
Console.WriteLine(new MyClass(var1)); //Line 34
Console.WriteLine(new MyClass(var2)); //Line 35
Console.WriteLine("Press any key to terminate.");
Console.ReadKey();
}//end main
}//end class Program
}//end namespace
The problem I'm having is twofold:
First, the error on line 34 and 35 keeps saying that there is no constructor in "MyClass" that takes one argument. So it's easy to deduce that, wow, I need a constructor that can take one argument in the class. I can make the constructor just fine, but the difficulty is in passing the "var1" and "var2". I believe I need to pass by reference here.
Secondly, I believe I need to take into consideration the fact that "var1" and "var2" are different variable types. This I really don't know what to do about. But the main question of this post is figuring out the first problem.
The limitation put on us by the instructor is that we are not allowed to change anything within the "Program" class.
The required output is as follows:
Display your first name here
Display your last name here
Press any key to terminate.
You can address the missing constructor issue like this:
public MyClass(bool First)
{
// your code here
}
public MyClass(int Last)
{
// your code here
}
Note that there is no return type specified, as constructors don't have returns. This will allow your constructor calls to run successfully.
I probably shouldn't be doing that, but, well... is this what you're trying to achieve?
class MyClass
{
private bool? _first;
private int? _last;
public MyClass(bool first)
{
_first = first;
}
public MyClass(int last)
{
_last = last;
}
public override string ToString()
{
if (_first != null)
return "FirstName";
if (_last != null)
return "LastName";
return String.Empty;
}
}
The problem is arising from the fact that you have your class name and method named the same. You cannot do this. Any properties or methods in your class must not be called the same as your class.
Your constructor issue is due to you calling new MyClass(var1). You did not specify a constructor in your class. That would look something like this:
public class MyClass
{
// This is a constructor that takes a parameter.
public MyClass(string myString)
{
}
// This is a constructor that takes 0 parameters.
// This exists if you do not specifically declare a constructor.
public MyClass()
{
}
}
What you are looking for here is called constructor overloading. You should make one constructor that accepts a bool as an argument and another that accepts an int.
It is a homework assignment, so I am not going to provide a sample. However, that should be enough to get you started.
Good luck.
Have a look at optional arguments. Using them, you could assign the arguments in the constructor default values (different from what will be sent by the program). Then, your program can send over either variable type and no error will be thrown regarding incorrect number of arguments or variable types.

C# Console program that contains a constant static field to display text in the output main method

Using C# for a console program in MicroSoft Visual Studio 2010, I have made some changes to this with some help from you guys and this console program is running correctly; however I need to implement a constant static field that will display the motto "To Obey the Girl Scout Law" in the output section of the main method. I know it must be something simple so please bear with me. When I include the public static const string Motto = "To Obey the Girl Scout Law" in the bass class, I get an error message - The constant 'DemoScouts.GirlScout.Motto' can not be static. The following is the complete code for this project:
public class GirlScout
{
public static const string Motto = "To Obey the Girl Scout Law";
public static string scoutName;
public static string enterName()
{
return scoutName;
}
public static int duesOwed;
public static int enterAmount()
{
return duesOwed;
}
public static int troopNumber;
public static int enterNumber()
{
return troopNumber;
}
}
class MainClass : GirlScout
{
static void Main()
{
Console.WriteLine();
Console.Write("Enter the Girl Scout's name: ");
GirlScout.scoutName = Console.ReadLine();
Console.WriteLine();
Console.Write("Enter their Troop Number: ");
string n = Console.ReadLine();
GirlScout.troopNumber = Int32.Parse(n);
GirlScout.enterNumber();
Console.WriteLine();
Console.Write("Enter the amount they Owe in Dues: $");
string d = Console.ReadLine();
GirlScout.duesOwed = Int32.Parse(d);
GirlScout.enterAmount();
Console.WriteLine();
// Seperate the input from the output:
Console.WriteLine();
Console.WriteLine(GirlScout.Motto);
Console.WriteLine("-----------------------------------------------");
Console.WriteLine();
// Display the new information:
Console.WriteLine("The name of the Girl Scout is: {0}", GirlScout.scoutName);
Console.WriteLine("The troop Number of the Girl Scout is: {0}", GirlScout.troopNumber);
Console.WriteLine("The amount of Dues Owed by this Girl Scout is: {0}", GirlScout.duesOwed);
// Keep the console window open in debug mode.
Console.ReadKey();
}
}
}
Any and all advice would be greatly appreciated.
You aren't doing anything with the name that the user entered:
Console.Write("Enter the Girl Scout's name: ");
Console.ReadLine();
It should be this:
Console.Write("Enter the Girl Scout's name: ");
GirlScout.scoutName = Console.ReadLine();
You also need to change the type of scoutName to be a string rather than an int.
You should also redesign your class. Use instance properties rather than static fields.
public class GirlScout
{
public string Motto { get; set; }
public string ScoutName { get; set; }
public int DuesOwed { get; set; }
public int TroopNumber { get; set; }
}
You are not storing the name the user input, as you do with the other data.
I don't see assignment to GirlScout.scoutName...
Side note: please consider not using static properties (unsless it is goal of assignment). Either create object with normal properties or not use them at all...
Well, you never initialized the value of scoutName, so what exactly do you expect to print?
I think you're missing a line of code like this:
GirlScout.scoutName = Console.ReadLine();
I have to say, though, that your class is designed very poorly. You have public data members, and your methods seem to have no purpose or meaning - you should brush up on encapsulation, and make your variables private. Use methods to change/get their values.
If you need any help ask in the comments or in another question.

classes and functions

I have 3 classes named maths, alphabets and main. The Maths Class contains Add function and alphabet class contains a function same as Maths class. But the third class is for calling the function which is used for calling the above functions defined in the above classes.
How it will work?
If the functions are static you'll have to explicitly tell which class they belong to - the compiler will be unable to resolve otherwise:
Maths.Add();
If they are not static the compiler will determine this based on the object type:
Maths maths = new Maths();
maths.Add(); // the necessary class and function will be resolved automatically
Is this what you mean?
public class Maths
{
public Maths() { }
public Double Add(Double numberOne, Double numberTwo)
{
return numberOne + numberTwo;
}
}
public class Alphabet
{
public Alaphabet() { }
public String Add(Char characterOne, Char characterTwo)
{
return characterOne.ToString() + characterTwo.ToString();
}
}
public void Main()
{
Alphabet alaphatbet = new Alphabet();
String alphaAdd = alphabet.Add('a', 'b'); // Gives "ab"
Maths maths = new Maths();
Double mathsAdd = maths.Add(10, 5); // Gives 15
}
By using an interface that defines an Add function and having Math and alphabets implement that interface.
C# programs do not contain "functions", but instead methods, which are attached to classes. So you call Math.Add or Alphabet.Add. Conflicting function names do not exist, in C#, for that reason. Conflicting class names are resolved by name spaces.

Categories

Resources