The name 'Inputname' does not exist in the current context - c#

I am a very very very basic programmer just starting off. I have followed a few tutorials and I am now trying to branch out into my own stuff but I keep getting the same Error that I cant rectify.
static void Main(string[] args)
{
///Call Method
OutWelcome();
///Return the name from getname method
Inputname = getname();
Console.WriteLine(" {0}", Inputname);
}
public static void OutWelcome()
{
Console.WriteLine("Welcome");
}
public static string getname()
{
///Declare Variable
string Inputname;
///Prompt User
Console.WriteLine("Enter your Name: ");
///Get name from user keyboard
Inputname = Console.ReadLine();
///Returns name
return Inputname;
}
}
I keep getting the following error "The name 'Inputname' does not exist in the current context. Line 18, 17 and 19
I know the answer will be so simple its n00b worthy, but I am new and we all have to start somewhere.
Thank you in advance
Sean

Please use the below code :
static void Main(string[] args)
{
///Call Method
OutWelcome();
///Return the name from getname method
string Inputname = getname();
Console.WriteLine(" {0}", Inputname);
}

Related

How to check and compare user input from console?

I have been trying to make a simple program to check a person's birthday and if their birthday is the same as their pet, for it to be printed out on the console, or if it's not the same to type out no valid input. I don't know why but the variables are not being taken in saying they aren't properly added or it just says they need a get/set. If anyone could show and explain how it should be done it would be like really awesome and cool and amazing. Here's the code:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Human human = new Human();
human.name();
human.age();
human.id();
human.birthday();
Robot robot = new Robot();
robot.id();
robot.model();
Pet pet = new Pet();
pet.name();
pet.birthday();
Program program = new Program();
program.BirthdayCheck("","");
}
public static void BirthdayCheck(string userResponse1, string userResponse2)
{
if (userResponse1 == userResponse2)
{
Console.WriteLine("" + userResponse1);
}
else
{
Console.WriteLine("No matching birthday");
}
}
interface IHuman
{
void name();
void age();
void id();
void birthday();
}
interface IRobot
{
void model();
void id();
}
interface IPet
{
void name();
void birthday();
}
class Human : IHuman
{
public string userResponse2;
public string Birthday
{
get { return userResponse2; }
set { userResponse2 = value; }
}
public void name()
{
Console.WriteLine("Citizen name: ");
Console.ReadLine();
}
public void age()
{
Console.WriteLine("Citizen's age: ");
Console.ReadLine();
}
public void id()
{
Console.WriteLine("Citizen's id: ");
Console.ReadLine();
}
public void birthday()
{
Console.WriteLine("Citizen's birthday: ");
userResponse2 = Console.ReadLine();
}
}
class Robot : IRobot
{
public void model()
{
Console.WriteLine("Enter Robot Model: ");
Console.ReadLine();
}
public void id()
{
Console.WriteLine("Enter Robot Id: ");
Console.ReadLine();
}
}
class Pet : IPet
{
public string userResponse1;
public string Birthday
{
get { return userResponse1; }
set { userResponse1 = value; }
}
public void name()
{
Console.WriteLine("Enter pet name: ");
Console.ReadLine();
}
public void birthday()
{
Console.WriteLine("Enter pet birthday: ");
userResponse1 = Console.ReadLine();
}
}
}
}
I had no issues with the interfaces themselves and it does that the information, it just doesn't want to compare the two between them. I don't know if it's just a logical or syntax error, but hopefully, it's at least partially correct. Finished up some syntax errors but the issues still remain. The error message that appears is "Member Program.BitrhdayCheck(string, string) cannot be accessed with an instance reference; qualify it with a type name instead."
As commented above, this looks like a really complicated program to compare something so simple. Assuming that's your choice, I think these two lines in the main method are not quite correct:
Program program = new Program();
program.BirthdayCheck("","");
you really should be calling the BirthdayCheck method directly.
Another issue is, no value is really being passed to this method. So not sure exactly what is it you're comparing.
Here's a fix to your main method that can solve your issue:
static void Main(string[] args)
{
Human human = new Human();
human.name();
human.age();
human.id();
human.birthday();
Robot robot = new Robot();
robot.id();
robot.model();
Pet pet = new Pet();
pet.name();
pet.birthday();
BirthdayCheck(pet.Birthday, human.Birthday); // birthdaycheck is method of the program class, hence does not need to be invoked with a new program object.
// Additionally, you need to pass an actual birthday value to compare instead of blank strings.
Console.ReadKey(); // this step ensures the console does not close after the birthday check
}
public static void BirthdayCheck(string userResponse1, string userResponse2)
{
if (userResponse1 == userResponse2)
{
Console.WriteLine("" + userResponse1);
}
else
{
Console.WriteLine("No matching birthday");
}
}
Here's an output sample of the program after the above mentioned changes:
Citizen name:
w
Citizen's age:
12
Citizen's id:
1
Citizen's birthday:
10/10/1990
Enter Robot Id:
2
Enter Robot Model:
r2d2
Enter pet name:
p2v2
Enter pet birthday:
11/11/1991
No matching birthday
userResponse1 and userResponse2 are out of scope from the BirthdayCheck method. you need to either pass in references to the human/pet objects(like human.userResponse2 == pet.userResponse1) or pass the birthdays themselves in to compare.
Is there a reason why you made this so complicated?
You made 3 classes and 3 interfaces and how do you expect them to work together?
You use Console.WriteLine(); without variables.
Does your code need to make sense? If its just for practice, you should
slow down and try something more simple, like 2 classes and then compare,
then 2 classes and 1 interface and then compare...
you mean
public string BirthdayCheck()
{
you were missing () from the method declaration

Can't set data into list and then print it.

I am trying to store data into a complex type list and then print it later. I am trying to use properties and then print it but it seems like I am missing something. Please help.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Color");
string color = Console.ReadLine();
Console.WriteLine("Enter transmition");
string transmition = Console.ReadLine();
Console.WriteLine("Enter Name");
string name = Console.ReadLine();
List<DatabaseCar> arr = new List<DatabaseCar> { };
DatabaseCar databaseCar = new DatabaseCar(color, transmition, name);
arr.Add(databaseCar);
foreach (DatabaseCar data in arr)
{
Console.WriteLine(data);
}
Console.ReadKey();
}
}
abstract class Data
{
protected string color;
protected string engine;
protected string name;
public abstract void set(string color, string engine, string name);
public string Color
{
get
{
return color;
}
}
public string Engine
{
get
{
return engine;
}
}
public string Name
{
get
{
return name;
}
}
}
class DatabaseCar : Data
{
public override void set(string color, string engine, string name)
{
this.color = color;
this.engine = engine;
this.name = name;
}
public DatabaseCar(string color, string engine, string name)
{
set(color, engine, name);
}
}
The result I get from it is:
Enter Color:
Red
Enter transmition:
Manual
Enter Name:
John
ConsoleApp1.DatabaseCar
This is because Console.WriteLine calls ToString() on an object that isn't specifically supported by one of its other overloads. ToString() by default returns the string representation of the Type.
To address this, you'll have to override ToString() with a custom implementation that does what you want.
public override string ToString()
{
// construct the representation that you want and return it.
}
Your problem is in the way you print your data.
foreach (DatabaseCar data in arr)
{
Console.WriteLine(data);
}
data is an instance of the type DatabaseCar, which is a class defined by you. It contains many different properties of different types. So you need to tell C# how to print it.
There's two ways to go about it. One, a dedicated method to print an object of type DatabaseCar. You can customize how the print is done, this is a very basic example.
static void PrintDatabaseCar(DatabaseCar car)
{
Console.WriteLine("Name : {0}", car.Name);
Console.WriteLine("Color : {0}", car.Color);
Console.WriteLine();
}
Then you can call that method from your main like so:
foreach (DatabaseCar data in arr)
{
PrintDatabaseCar(data);
}
Option two, you can override the ToString() method and provide functionality to print an object of type DatabasCar. This method has to go in your DatabaseCar class definition.
class DatabaseCar : Data
{
public override void set(string color, string engine, string name)
{
this.color = color;
this.engine = engine;
this.name = name;
}
public DatabaseCar(string color, string engine, string name)
{
set(color, engine, name);
}
public override string ToString()
{
string result = string.Empty;
result += string.Format("Name : {0}", name) + Environment.NewLine;
result += string.Format("Color : {0}", color) + Environment.NewLine;
result += Environment.NewLine;
return result;
}
}
Got it.
Thanks Everyone
public override string ToString()
{
// construct the representation that you want and return it.
return String.Format("Color {0},Engine {1}, Name {2}",color,engine,name);
}

Can i Do object reflection in C#

I have two classes, Dog and Cat
class Dog
{
public void speak() {
System.out.println("Woof!");
}
}
class Cat
{
public void speak() {
System.out.print("Meow!");
}
}
In my main, I take the name as String, either "Cat", or "Dog".
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
String name = sc.next();
Class<?> cls = Class.forName(name);
Object object = cls.newInstance();
}
Can i do this in C#??
Line by line it would be:
public static void Main(string[] args)
{
string name = Console.ReadLine();
// The second true will ignore case
var cls = Type.GetType("Animals." + name, true, true);
var #object = Activator.CreateInstance(cls);
}
with the various animals like:
namespace Animals
{
public class Dog
{
public void speak()
{
Console.WriteLine("Woof!");
}
}
public class Cat
{
public void speak()
{
Console.WriteLine("Meow!");
}
}
}
I've added a namespace to make it a "more complete" example: in .NET you can have your code *outside" any namespace, but normally you'll use a namespace. I'm prepending it to the name of the class obtained from the console ("Animals." + name).
Note that this code is quite useless, because without a base interface/class, you can't easily make them speak() (you can go full reflection/dynamic from this point onward to do it but it is "bad")
Bad way with dynanic:
dynamic #object = Activator.CreateInstance(cls);
#object.speak();
(note that I'm not supporting what you are doing, it is bad in multiple ways)

Cannot convert from method group to Int32

I want my small math program to look really sleek, and by this I mean under the Main method I have the following methods:
Greet()
UserInput1()
UserInput2()
Result()
In Greet() I just say "HI", in UserInput1() I want to collect the first number, in UserInput2() I want to collect the second number, and in Result() I want to print the result of UserInput1 + UserInput2. I can collect the number in UserInput 1 and 2 but I can’t seem to send them to Result() without assigning values to them under the Main() function.
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Greet();
firstNumber();
secondNumber();
result(firstNumber, secondNumber);
Console.ReadKey();
}
public static void Greet()
{
Console.WriteLine("Hello, pls insert two numbers");
}
public static int firstNumber()
{
int num01 = Convert.ToInt32(Console.ReadLine());
return num01;
}
public static int secondNumber()
{
int num02 = Convert.ToInt32(Console.ReadLine());
return num02;
}
public static void result( int num01, int num02)
{
Console.WriteLine(num01 + num02);
}
}
}
change this:
result(firstNumber, secondNumber);
to this:
result(firstNumber(), secondNumber());
and remove the calls to the 2 methods in the two lines above.
To call a method without parameters, you need the parentheses without content.
Cannot convert from method group to int
This error message occurs when you attempt to take a method (without invocation) and pass it as a type. The result method is expecting two parameters of type int, but you're attempting to pass it the method, rather than the result of the method invocation.
You need to store the results in a variable, or invoke the methods with the ():
Like this:
static void Main(string[] args)
{
Greet();
var first = firstNumber();
var second = secondNumber();
result(first , second );
Console.ReadKey();
}
or this:
static void Main(string[] args)
{
Greet();
result(firstNumber(), secondNumber());
Console.ReadKey();
}
Call the method like the following, So that the method result will be called with output from the firstNumber() and secondNumber() as well :
result(firstNumber(),secondNumber());
Few more suggestions:
Make the method Greet() to a re-usable one by passing appropriate message and then display it. so that you can use the same for all display operations. the signature of the method will be:
public static void Greet(string message)
{
Console.WriteLine(message);
}
The method Convert.ToInt32() will convert the given input to an integer value only if the input is convertible. else it will throws FormatException. So i prefer you to use int.TryParse for this purpose. Which will help you to determine whether the conversion is success or not. so the Method signature for firstNumber() will be like the following:
public static int firstNumber()
{
int num01=0;
if(!int.TryParse(Console.ReadLine(),out num01))
{
Greet("Invalid input");
}
return num01;
}
Hope that you will change the secondNumber() as well

Error CS1001 (Identifier expected)

I'm new to programming and am taking a C# class. I am getting compiler error CS1001 when I try to write this program.
I read the Compiler Error description (link below), but I'm really not getting it. What am I doing wrong?
http://msdn.microsoft.com/en-us/library/b839hwk4.aspx
Here is my source code:
using System;
public class InputMethodDemoTwo
{
public static void Main()
{
int first, second;
InputMethod(out first, out second);
Console.WriteLine("After InputMethod first is {0}", first);
Console.WriteLine("and second is {0}", second);
}
public static void InputMethod(out first, out second)
// The error is citing the line above this note.
{
one = DataEntry("first");
two = DataEntry("second");
}
public static void DataEntry(out int one, out int two)
{
string s1, s2;
Console.Write("Enter first integer ");
s1 = Console.ReadLine();
Console.Write("Enter second integer ");
s2 = Console.ReadLine();
one = Convert.ToInt32(s1);
two = Convert.ToInt32(s2);
}
}
According to the instructions, I'm supposed to have a method b (InputData) which pulls statements from method c (DataEntry)... Here are the instructions:
The InputMethod()in the InputMethodDemo program in Figure 6-24 contains repetitive
code that prompts the user and retrieves integer values. Rewrite the program so the
InputMethod()calls another method to do the work. The rewritten InputMethod()
will need to contain only two statements:
one = DataEntry("first");
two = DataEntry("second");
Save the new program as InputMethodDemo2.cs."
The InputMethodDemo they are referring to is the same program, except that it calls only one method (the InputMethod) instead of two.
The text I referred to above is "Microsoft® Visual C#® 2008, An Introduction to Object-Oriented Programming, 3e, Joyce Farrell"
Any advice/ help would be greatly appreciated.
This is what you are expected to do:
using System;
public class InputMethodDemoTwo
{
public static void Main()
{
int first, second;
InputMethod(out first, out second);
Console.WriteLine("After InputMethod first is {0}", first);
Console.WriteLine("and second is {0}", second);
Console.ReadLine();
}
public static void InputMethod(out int first, out int second)
//Data type was missing here
{
first = DataEntry("first");
second = DataEntry("second");
}
public static int DataEntry(string method)
//Parameter to DataEntry should be string
{
int result = 0;
if (method.Equals("first"))
{
Console.Write("Enter first integer ");
Int32.TryParse(Console.ReadLine(), out result);
}
else if (method.Equals("second"))
{
Console.Write("Enter second integer ");
Int32.TryParse(Console.ReadLine(), out result);
}
return result;
}
}
Change
public static void InputMethod(out first, out second)
{
one = DataEntry("first");
two = DataEntry("second");
}
to
public static void InputMethod(out DataEntry first, out DataEntry second)
{
first = DataEntry("first");
second = DataEntry("second");
}
You haven't provided the type of the arguments. Also, your arguments are called first and second, not one and two.

Categories

Resources