i have fixed the question:
The code is working until it hit the MultyMethod it stop because i have tried to take the output from the SumMethod and do another calculation in the MultyMethod.
So my question is i have tried to use the same input from SumMethod in the MultyMethod but it does not work well i have used all the reference in my mind or i could think of but still it told me : the name "SumMethod" need a reference to call it or you forgetting to use a reference. So how i could use the same input from the SumMethod in the MultyMethod!!
using System;
namespace example
{
class Program
{
public int number1 { set; get; }
public int number2 { set; get; }
public int sum { set; get; }
public int multy { set; get; }
static void Main(string[] args)
{
var value = SumMethod();
var values = MultyMethod();
ResultMethod(value.number1, value.number2, value.sum, values.multy);
}
public static Program SumMethod()
{
var input = new Program();
int i = 0;
Console.WriteLine(" Please Enter your first number: ");
input.number1 = int.Parse(Console.ReadLine());
Console.WriteLine(" Please Enter your second number: ");
input.number2 = int.Parse(Console.ReadLine());
int[] arr = new int[] { input.number1, input.number2 };
do
{
input.sum += arr[i];
i++;
} while (i < 2);
return input;
}
public static Program MultyMethod()
{
var input = new Program();
// here is the issue i am trying to get the input from the previous method instead of asking the user to input the numbers again
// i have tried this
//input.number1 = new input.SumMethod();
// and also have tried to use this reference
//value.SumMethod(); // since the inputs store in this variable but it does not make since to call it this way ><
// i have also tried to use this way
//input.number1 = new SumMethod();
return input;
}
public static void ResultMethod(int number1, int number2, int sum, int multy)
{
Console.WriteLine(" The first number is: ");
Console.WriteLine(number1);
Console.WriteLine(" The second number is: ");
Console.WriteLine(number2);
Console.WriteLine(" The sum of the number is: ");
Console.WriteLine(sum);
Console.WriteLine(" The multiplication of the numbers is: ");
Console.WriteLine(multy);
}
}
}
Okay, your basic problem is that the variable input, which you wish to reference in MultyMethod, is internal to SumMethod. Therefore, MultyMethod can't access it.
You define another variable called input in MultyMethod, but that is NOT the same variable. It's a separate one, the scope of which is just MultyMethod, and can't be accessed outside of it.
So, how to do what you want. I hope you don't mind that I'm also going to make some suggestions about how you could better organize this code.
First, you could define input outside of SumMethod, as a class-level static variable. In that case, it could be accessed by both SumMethod and MultyMethod. The following is a short excerpt (with some lines removed to save space):
class Program
{
public int number1 { set; get; }
public int number2 { set; get; }
public int sum { set; get; }
public int multy { set; get; }
public static Program input = null;
static void Main(string[] args)
{
// etc.
}
public static Program SumMethod()
{
input = new Program();
// rest of the code
return input;
}
public static Program MultyMethod()
{
input = Program.input; // this is a static reference.
// desired multiplication code
return input;
}
Another option would be to parameterize MultyMethod so it takes a Program as a parameter, representing the input:
public static Program MultyMethod(Program input)
{
// You probably don't want to have the same variable have both your sum
// and your multiplication results.
Program newVar = new Program() { number1 = input.number1, number2 = input.number2 };
// Do things with newVar in place of "input"
return newVar;
}
Then you'd change Main to look like this:
var value = SumMethod();
var values = MultyMethod(value);
An even better version would separate getting the input from performing the summing. So you could do this:
static void Main(string[] args)
{
var input = GetInput();
var value = SumMethod(input);
var values = MultyMethod(input);
// do other things
}
Finally, the whole thing would be better if you had separate classes for all three of the following:
The program itself
The input parameters and results
The multiplication and sum methods
Related
I have a very strange Behavior when merging two arrays together:
Assumptions
I have a class Tensor which contains an array float[] and a function AddTensorElements:
class Tensor
{
public float[] MovingAverage3h { get; set; }
public float[] MovingAverage6h { get; set; }
public float[] MovingAverage1d { get; set; }
public void AddTensorElements(Tensor input)
{
if (this.MovingAverage3h == null)
this.MovingAverage3h = input.MovingAverage3h;
this.MovingAverage6h = input.MovingAverage6h;
this.MovingAverage1d = input.MovingAverage1d;
}
else
{
this.MovingAverage3h = Concat(this.MovingAverage3h, input.MovingAverage6h);
this.MovingAverage6h = Concat(this.MovingAverage6h, input.MovingAverage6h);
this.MovingAverage1d = Concat(this.MovingAverage1d, input.MovingAverage1d);
}
private float[] Concat (float[] first, float[] second)
{
List<float> concatenated = new List<float>();
concatenated.AddRange(first);
concatenated.AddRange(second);
//foreach (float value in first) concatenated.Add(value);
//foreach (float value in second) concatenated.Add(value);
float[] returnArray = concatenated.ToArray();
return returnArray;
}
}
Within my main program, I repeatedly add the tensor M6t to the base tensor Minutes30[i]
class TensorCreator
{
private static List<Elements.Tensor> Minutes30 = new List<Elements.Tensor>();
private static void AddValues(Tensor M6t)
{
// Fill Minutes 30
Minutes30.Add(M6t);
for (int i = CounterM30; i < Minutes30.Count-1; i += M6)
{
{ } // Issue come up right here
Minutes30[i].AddTensorElements(M6t);
{ } // Issue come up right here
}
}
public static void AppendDataToTensor(Elements.Tensor queueElement)
{
// ...
AddValues(M6Avg);
}
}
Expected behavior vs actual behavior
The array within Minutes[i] expands
The array within M6t staysfloat[1]
So far so good, this works in a tiny separate test application
Within my actual application, the same code lets the baseTensor expand but also the input tensor gets expanded!
for (int i = CounterM30; i < Minutes30.Count-1; i += M6)
{
// M6T.Length == 1;
Minutes30[i].AddTensorElements(M6t);
// M6T.Length == Minutes30[i].Length;
}
strangely, whitin AddtensorToElements() I can see the values changing as well:
The Issue lies right here:
Minutes30.Add(M6t);
This adds a reference of Class Tensor M6t to Minutes 30. The result is that Minutes30[i] gets concatenated with it self.
Solution:
In class Tensor, add a Clone() method
public Tensor Clone()
{
Tensor tensor = new Tensor();
tensor.MovingAverage3h = this.MovingAverage3h.ToArray();
tensor.MovingAverage6h = this.MovingAverage6h.ToArray();
tensor.MovingAverage1d = this.MovingAverage1d.ToArray();
return tensor;
}
then change
Minutes30.Add(M6t);
to
Minutes30.Add(M6t.Clone());
I want to make an application where I can type a word and then a number. After typing all I want I want an output of them sorted alphabetical. The problem is that the words sort but the numbers don't sort with them because they are 2 different lists. How can i merge this 2 lists? I don't want to add them together like AddRange I need the out put like Console.WriteLine ("x{0}+" "+"{1}", numbers, words.
I've tried words.Sort(); but it just sorted the words and not both. So how can I merge the 2 lists?
The question is probably clear but in case you need some code there it is:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace zutaten
{
namespace mengen
{
class Program
{
static int hello;
static List<string> zutaten = new List<string>();
static List<int> mengen = new List<int>();
public static int memo;
public static int d = 1;
static List<string> zusammen = new List<string>();
static public bool Main(string[] args)
{
bool fertig = false;
while (!fertig)
{
var wert = Console.ReadLine();
if (wert != "f")
{
if (Gleich(zutaten, mengen))//zutaten.Count == mengen.Count)
{
if (KeineZutaten(wert))//int.TryParse(wert, out int keineZutat))
{
KeineZutatenAussage(wert);
}
else
{
if (Beinhaltet(wert)) //zutaten.Contains(wert)
{
Removen(wert);
// int index = zutaten.IndexOf(wert);
// zutaten.RemoveAt(index);
// mengen.RemoveAt(index);
}
//-------
Zutathinzufügen(wert);
//zutaten.Add(wert);
}
}
else
{
if (ParseMenge(wert, out memo))//int.TryParse(wert, out int menge))
{
Mengehinzufügen(memo);// mengen.Add(menge);
}
else
{
Mengepluseins(mengen);
//mengen.Add(1);
//--------
if (Beinhaltet(wert))
{
Removen(wert);
// int index = zutaten.IndexOf(wert);
// zutaten.RemoveAt(index);
// mengen.RemoveAt(index);
}
//------
Zutathinzufügen(wert);
//zutaten.Add(wert);
}
}
}
else
{
fertig = Fertigt();
if (!Gleich(zutaten, mengen))
{
Mengepluseins(mengen);
}
Forschleife(zutaten);
//for (int i = 0; i < zutaten.Count; i++)
//{
// Console.WriteLine("x{0} {1}", mengen[i], zutaten[i]);
//}
}
}
}
public static string MeineMethode()
{
return "string";
}
public static bool Gleich(List<string> variable1, List<int> variable2)
{
return variable1.Count == variable2.Count;
}
public static bool KeineZutaten(string wert1)
{
return int.TryParse(wert1, out hello);
}
public static void KeineZutatenAussage(string wert2)
{
Console.WriteLine("{0} ist keine Zutat", wert2);
}
public static bool Beinhaltet(string hulu)
{
return zutaten.Contains(hulu);
}
public static void Removen(string wertt)
{
int index = zutaten.IndexOf(wertt);
zutaten.RemoveAt(index);
mengen.RemoveAt(index);
}
public static void Zutathinzufügen(string werttt)
{
zutaten.Add(werttt);
}
// int index = zutaten.IndexOf(wert);
// zutaten.RemoveAt(index);
// mengen.RemoveAt(index);
//int.TryParse(wert, out int keineZutat
//zutaten.Add(wert);
public static bool ParseMenge(string wert1, out int var2)
{
return int.TryParse(wert1, out var2);
}
//int.TryParse(wert, out int menge))
public static void Mengehinzufügen(int var1)
{
mengen.Add(var1);
}
// mengen.Add(menge);
public static void Mengepluseins(List<int> mengen)
{
mengen.Add(d);
}
//mengen.Add(1);
public static bool Fertigt()
{
return true;
}
//fertig = true;
public static bool Mengeungleichzutaten(List<string> variable1, List<int> variable2)
{
return variable1.Count != variable2.Count;
}
//if (mengen.Count != zutaten.Count)
//{
// mengen.Add(1);
//}
public static void Forschleife(List<string> hey)
{
zutaten.Sort();
for (int i = 0; i < hey.Count; i++)
{
Console.WriteLine("x{0}"+" "+"{1}, mengen[i], zutaten[i]);
}
}
Input example :
Pork[Enter]
3[Enter]
Tomatoes[Enter]
6[Enter]
Potatoes[Enter]
2[Enter]
Expected output :
3x Pork
2x Potatoes
6x Tomatoes
Current output :
3x Pork
6x Potatoes
2x Tomatoes
Assuming these can be arrays, then you can use the native sort command to sort the two arrays according to one of them. This example sorts by the scores:
static void Main(string[] args)
{
int[] classScores = new int[]{30,50,25,39,62};
string[] studentNames = new string[]{"Jim","John","Mary","Peter","Sarah"};
Array.Sort(classScores, studentNames); // sort both according to scores
for (int i = 0; i < classScores.Length; i++)
{
Console.WriteLine(classScores[i] + " " + studentNames[i]);
}
}
You can use a SortedDictionary to store your values. The key being the product name, the value its quantity. This will be automatically sorted by key.
static SortedDictionary<string, int> GetProducts()
{
// Type of the
// key
// | Type of the
// | value
// | |
// v v
var Products = new SortedDictionary<string, int>();
while (true)
{
var product = "";
int quantity;
// First, ask the user to enter a product. If he enters nothing, ask again
while (product == "")
{
Console.WriteLine("Please enter a product name or f to finish");
product = Console.ReadLine();
if (product == "f")
return Products; // we are done, we can return the SortedDictionary
}
// Now, get the quantity
do
{
Console.WriteLine($"Please enter a quantity for {product}");
// Ask again if the user enters an invalid number
} while (!Int32.TryParse(Console.ReadLine(), out quantity));
// Store the informations in the SortedDictionary
Products[product] = quantity;
}
}
public static void Main()
{
// Get the products
var Products = GetProducts();
// Display them
foreach (var key in Products.Keys)
Console.WriteLine($"{Products[key]}x {key}");
}
Input :
Please enter a product name or f to finish
Pork
Please enter a quantity for Pork
3
Please enter a product name or f to finish
Tomatoes
Please enter a quantity for Tomatoes
6
Please enter a product name or f to finish
Potatoes
Please enter a quantity for Potatoes
2
Please enter a product name or f to finish
f
Output :
3x Pork
2x Potatoes
6x Tomatoes
using System;
using System.Collections.Generic;
using System.IO;
namespace _2._1
{
class Narys
{
public string Vardas { get; set; }
public string Pavarde { get; set; }
public double Pinigai { get; set; }
public Narys()
{
}
public Narys(string vardas, string pavarde, double pinigai)
{
Vardas = vardas;
Pavarde = pavarde;
Pinigai = pinigai;
}
List<Narys> DuomenuSkaitymas()
{
List<Narys> nariai = new List<Narys>();
string[] eilutes = File.ReadAllLines(#"nariai.txt");
foreach (string eilute in eilutes)
{
string[] duomenys = eilute.Split(' ');
string vardas = duomenys[0];
string pavarde = duomenys[1];
double pinigai = double.Parse(duomenys[2]);
Narys narys = new Narys(vardas, pavarde, pinigai);
nariai.Add(narys);
}
return nariai;
}
void DuomenuIrasymas(List<Narys> nariai)
{
string[] eilutes = new string[nariai.Count];
for (int i = 0; i < nariai.Count; i++)
{
eilutes[i] = String.Format("{0} {1} {2}", nariai[i].Vardas, nariai[i].Pavarde, nariai[i].Pinigai);
}
File.WriteAllLines(#"nariaiAts.txt", eilutes);
}
void DuomenuParodymas(List<Narys> nariai)
{
foreach (Narys narys in nariai)
{
Console.WriteLine("Vardas: {0}\nPavarde: {1}\nPinigai: {2}", narys.Vardas, narys.Pavarde, narys.Pinigai);
}
}
}
class Program
{
static void Main(string[] args)
{
Program p = new Program();
List<Narys> nariai = p.DuomenuSkaitymas();
p.DuomenuIrasymas(nariai);
}
}
}
And why i'm getting those errors ?
I think it should work, but it isn't, so i guess you will be able to solve this sh*t. Also, i'm studying in university and i am doing this by example and it really should work. I think there should be enough info for you guys.
Just look at your code:
class Program
{
static void Main(string[] args)
{
Program p = new Program();
List<Narys> nariai = p.DuomenuSkaitymas();
p.DuomenuIrasymas(nariai);
}
}
You are declaring the class Program that contains only a static method. Then you instantiate that class in variable p. Then you are trying to access some DuomenuSkaitymas method of it. But it contains only a static method. So how should this work?
You probably wanted to instantiate class Narys in p instead of Program.
Just a pro tip: never use identifier names in your local language, even if it looks more understandable at first. Your code might well end in the hands of others who don't understand your language. Believe me, you will choose better identifiers if you want others to understand your code - and that will be valuable to you too.
Your class Program just contains the main() method, so the IDE informs you that Program does not contains DuomenuSkaitymas method.
That method (DuomenuSkaitymas) , is defined in the Nary's class, so probably you need to modify you main method to
class Program
{
static void Main(string[] args)
{
Narys p = new Narys();
List<Narys> nariai = p.DuomenuSkaitymas();
p.DuomenuIrasymas(nariai);
}
}
I didn't check what the program means itself just clarifying your CS1061, so if there is other problems try to look closely to the code and understand what it means. If any other issue non related to this CS1061 arises after that you could try to post a new question with your issues or ideas about it.
So I have coded for a while I C# and learned the basics, one thing that always stops me is how I can create a class and then use a list for a user to input values.
I don't know if I'm totally off the chart with this code, the problem is that I don't understand why I can't use my newly created object of the class and add input to it. All help is appreciated
class Program
{
static void Main(string[] args)
{
List<Citizen> listOfCitizens = new List<Citizen>();
for (int i = 0; i < listOfCitizens.Count; i++)
{
Console.WriteLine("Enter Surname for the citizen:");
listOfCitizens.SurName.add = Console.ReadLine();
Console.WriteLine("Enter Lastname for the citizen:");
listOfCitizens.Lastname.add = Console.ReadLine();
Console.WriteLine("Enter age of the citizen:");
listOfCitizens.age.add = int.Parse(Console.ReadLine());
}
Console.WriteLine($"Name {Citizen.SurName} {Citizen.LastName} {Citizen.age}");
Console.Read();
}
}
class Citizen
{
public static string SurName{ get; set; }
public static string LastName{get;set;}
public static int age { get; set; }
}
A list of something is not a something. Just like a basket of apples is not an apple. You don't eat the basket, you eat an item from the basket.
So when you create your list:
List<Citizen> listOfCitizens = new List<Citizen>();
You would then create an item to add to the list:
Citizen someCitizen = new Citizen();
someCitizen.SurName = "Smith";
// etc.
And then add it to the list:
listOfCitizens.Add(someCitizen);
Additionally, your Citizen is a little off. Those properties shouldn't be static. Not sure why you made them that way, but you should remove the static keyword from everything in your Citizen class.
I saw an example on MSDN where it would let you specify the default value if nothing is returned. See below:
List<int> months = new List<int> { };
int firstMonth2 = months.DefaultIfEmpty(1).First();
Is it possible to use this functionality with an object? Example:
class object
{
int id;
string name;
}
code:
List<myObjec> objs = new List<myObjec> {};
string defaultName = objs.DefaultIfEmpty(/*something to define object in here*/).name;
UPDATE:
I was thinking I could do something like this:
List<myObjec> objs = new List<myObjec> {};
string defaultName = objs.DefaultIfEmpty(new myObjec(-1,"test")).name;
But haven't been able to. It should be noted that I am actually trying to use this method on an object defined in my DBML using LINQ-To-SQL. Not sure if that makes a difference in this case or not.
You need to pass an instantiated class as a parameter of the DefaultIfEmpty.
class Program
{
static void Main(string[] args)
{
var lTest = new List<Test>();
var s = lTest.DefaultIfEmpty(new Test() { i = 1, name = "testing" }).First().name;
Console.WriteLine(s);
Console.ReadLine();
}
}
public class Test
{
public int i { get; set; }
public string name { get; set; }
}
To add to it and make it a bit more elegant (IMO) add a default constructor:
class Program
{
static void Main(string[] args)
{
var lTest = new List<Test>();
var s = lTest.DefaultIfEmpty(new Test()).First().name;
Console.WriteLine(s);
Console.ReadLine();
}
}
public class Test
{
public int i { get; set; }
public string name { get; set; }
public Test() { i = 2; name = "testing2"; }
}
As per the MSDN page on this Extension Method you can do what you want:
http://msdn.microsoft.com/en-us/library/bb355419.aspx
Check the sample on this page for an example on how to use this with an object.
i must admit i am not too sure i understand your question, but i'll try to suggest using double question mark if the returned object might be null. Like so:
myList.FirstOrDefault() ?? new myObject();
You can create a default Object Like this:
Object o_Obj_Default = new Object();
o_Obj_Default.id = 3;
o_Obj_Default.name = "C";
And add it to your default value :
string defaultName = objs.DefaultIfEmpty(o_Obj_Default).First().name;
If your list "objs" is empty, the result will be "C"