Accessing output function in mian without static keyword - c#
In this code I made two output functions and one main.
When I call output function in main the program give the error.
using System;
public class InitArray
{
public static void Main()
{
int[,] rectangular = { { 1, 3, 4 }, { 5, 2, 4 } };
int[][] jagged = { new int[] { 2, 3, 4 }, new int[] { 3, 4, 5 }};
}
public void OutputArray(int [,]array)
{
for(int row=0;row<array.GetLength(0);row++)
{
for (int column = 0; column < array.GetLength(1); column++)
Console.Write("{0} ", array[row, column]);
Console.WriteLine();
}
}
public void OutputArray(int [][]array)
{
foreach(var row in array)
{
foreach (var element in row)
Console.Write("{0} ", element);
Console.WriteLine();
}
}
}
This is main function and have two arrays one is jagged and other is rectangular type.
The defined function is without static keyword and I could not access in main function.
This second output function is also a non static function and this is also not access in main.
Anyone can tell me the the reason?
Non-static methods want instance; that's why either mark the method as static:
public static void OutputArray(int[][] array) {
...
}
public static void Main() {
...
OutputArray(...);
...
}
or create and provide the instance:
public void OutputArray(int[][] array) {
...
}
public static void Main() {
...
var instance = new InitArray();
instance.OutputArray(...);
...
}
Related
Passing two 2dimensional arrays to method one after the other, C#
I want to run my Sudoku checker (written in method CheckSudokuSolution on the bottom) with two sudoku solutions. i'm not very experienced in passing parameters and although my research cannot do that: I need to pass to method CheckSudokuSolution first my 1. Sudoku (in Solution1) and then the second (in Solution2). Should I change something with the Solution1(), Solution2()? If you have time for explainment, I would be happy. Thanks. My program: static void Main(string[] args) { CheckSudokuSolution(s); CheckSudokuSolution(s); Console.ReadKey(true); } static void Solution1() { int[,] s = new int[,] { { 4,3,5,2,6,9,7,8,1}, { 6,8,2,5,7,1,4,9,3}, { 1,9,7,8,3,4,5,6,2}, { 8,2,6,1,9,5,3,4,7}, { 3,7,4,6,8,2,9,1,5}, { 9,5,1,7,4,3,6,2,8}, { 5,1,9,3,2,6,8,7,4}, { 2,4,8,9,5,7,1,3,6}, { 7,6,3,4,1,8,2,5,9} }; } static void Solution2() { int[,] s = new int[,] { { 1,5,2,4,8,9,3,7,6}, { 7,3,9,2,5,6,8,4,1}, { 4,6,8,3,7,1,2,9,5}, { 3,8,7,1,2,4,6,5,9}, { 5,9,1,7,6,3,4,2,8}, { 2,4,6,8,9,5,7,1,3}, { 9,1,4,6,3,7,5,8,7}, { 6,2,5,9,4,8,1,3,7}, { 8,7,3,5,1,2,9,6,4} }; } static void CheckSudokuSolution(int[,] s ) { // code }
In Main(), you have no variable named s, so you get an error with what you currently have. I suggest making Solution1 a static variable instead of a function: static int[,] Solution1 = new int[,] { { 4,3,5,2,6,9,7,8,1}, { 6,8,2,5,7,1,4,9,3}, { 1,9,7,8,3,4,5,6,2}, { 8,2,6,1,9,5,3,4,7}, { 3,7,4,6,8,2,9,1,5}, { 9,5,1,7,4,3,6,2,8}, { 5,1,9,3,2,6,8,7,4}, { 2,4,8,9,5,7,1,3,6}, { 7,6,3,4,1,8,2,5,9} }; Now you can pass it in directly: CheckSudokuSolution(Solution1); Similarly for Solution2.
Not sure to get the all point there but you can use class in first place to see your arrays from the main then : Send your arrays to CheckSudokuSolution(). Check the return value. Exemple : static void Main(string[] args) { int[,] s1 = CheckSudokuSolution(Solutions.s1); int[,] s2 = CheckSudokuSolution(Solutions.s2); // display sudoku s1 int i = 0; foreach (var item in s1) { if (i == 9) { Console.WriteLine(); i = 0; } Console.Write(item.ToString()); i++; } Console.ReadKey(true); } public static class Solutions { public static int[,] s1 = new int[,] { { 4,3,5,2,6,9,7,8,1}, { 6,8,2,5,7,1,4,9,3}, { 1,9,7,8,3,4,5,6,2}, { 8,2,6,1,9,5,3,4,7}, { 3,7,4,6,8,2,9,1,5}, { 9,5,1,7,4,3,6,2,8}, { 5,1,9,3,2,6,8,7,4}, { 2,4,8,9,5,7,1,3,6}, { 7,6,3,4,1,8,2,5,9} }; public static int[,] s2 = new int[,] { { 1,5,2,4,8,9,3,7,6}, { 7,3,9,2,5,6,8,4,1}, { 4,6,8,3,7,1,2,9,5}, { 3,8,7,1,2,4,6,5,9}, { 5,9,1,7,6,3,4,2,8}, { 2,4,6,8,9,5,7,1,3}, { 9,1,4,6,3,7,5,8,7}, { 6,2,5,9,4,8,1,3,7}, { 8,7,3,5,1,2,9,6,4} }; } static int[,] CheckSudokuSolution(int[,] s) { // Do something with s return s; } }
Loop through a list of integers - only returning 1 number
Trying to simply loop through a list of ints, and printing each number via returnNumbers() however it only loops through the list one, returning the first element. Can anyone detect the minor mistake I'm making? class Program { static void Main(string[] args) { ListHolder List = new ListHolder(); List.addNumber(6); List.addNumber(3); List.addNumber(2); List.returnNumbers(); } } class ListHolder { List<int> numbers = new List<int>(); public void addNumber(int val) { numbers.Add(val); } public void returnNumbers() { foreach (int n in numbers) { Console.WriteLine(n); Console.ReadLine(); } } }
Move the Console.Readline() out of your loop. It's only displaying once because the program is waiting for your input. The way you've written it, you'd have to input something (let's say just hitting the Enter key) to see each output. using System.IO; using System; using System.Collections.Generic; class Program { static void Main(string[] args) { ListHolder List = new ListHolder(); List.addNumber(6); List.addNumber(3); List.addNumber(2); List.returnNumbers(); Console.ReadLine(); } } class ListHolder { List<int> numbers = new List<int>(); public void addNumber(int val) { numbers.Add(val); } public void returnNumbers() { foreach (int n in numbers) { Console.WriteLine(n); //Console.ReadLine(); } } }
Can't Call arrays in main method
I'm practicing methods, but the problem is I want to separate inputting and sorting, the display method will be the main, I'm having trouble fixing this calling from other class. This is my script : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaseProblem { class Method { static void MethodInput() { int[] array = new int[5]; int i; // loop for accepting values in array for (i = 0; i < 5; i++) { Console.Write("Enter number:\t"); array[i] = int.Parse(Console.ReadLine()); } } public static void MethodSort() { foreach (int i in array) { Console.Write(" {0}", i); } } } class Program { static void Main(int[]array) { //sorting array value; Array.Sort(array); //use array's sort function Method.MethodSort(array); Console.ReadLine(); } } } Thank you for your help
First of all Main() ( or "EntryPoint" as we should call it ) cannot have int[] as an input parameter but string[] instead you should learn basics of programming before starting to actually code something. Second thing : I want to separate inputting and sorting You can create an object called Input public class Input { public static void Write(string message) { Console.WriteLine(message); } public static int? ReadInt(string reason) { Write(reason); string userInput = Console.ReadLine(); int parsed = 0; if(int.TryParse(userInput, out parsed)) return (int?)parsed; return null; } } This will be your "InputLogic" which you can use as Input.ReadInt("Please specify your age: "); Next you can make an Operations object : public class Operations { public void Display(int[] arr) { foreach(int i in arr) { // and since you have "Input" class that can display things Input.Write(i.ToString()); } } public void Sort(ref int[] arr) { Array.Sort(arr); } } Now the last thing is to combine it within your Program class Program { static void Main(string[] args) { int[] arr = new int[5]; for(int i = 0; i < arr.Length; i++) { int? input = null; while( !( input = Input.ReadInt("Give me number") ).HasValue ) { } arr[i] = input.Value; } Operations op = new Operations(); op.Display(arr); op.Sort(ref arr); op.Display(arr); } }
Well, you are missing the parameter for the called function. public static void MethodSort(int[] array) { foreach (int i in array) { Console.Write(" {0}", i); } } note: not tested
Okay, you have two errors, both in this method: public static void MethodSort() { foreach (int i in array) { Console.Write(" {0}", i); } } as well as how you call it: Method.MethodSort(array); The first problem is that the method uses the variable array, which doesn't exist in that method's scope. The second problem is that you are passing array to the call to Method.MethodSort, but that method isn't configured to take a parameter. There are two ways to approach solving this: remove array entirely, or change the method to accept it. Now, you obviously cannot remove array, as the whole point is to do stuff with it. Therefore, the logical solution is to add array as a parameter to your method: public static void MethodSort(int[] array) { foreach (int i in array) { Console.Write(" {0}", i); } }
Access into global variable by Console.Readline() in C#
I'm trying to improve my program for Fibonacci numbers using of memoization: public class MyGlobals { public long TotNum { get; set; } public long[] MyNumbers { get; set; } public void GetParam() { Console.Write("n = "); this.TotNum = long.Parse(Console.ReadLine()); this.MyNumbers = new long[this.TotNum + 1]; // set all numbers to -1 for (int i = 0; i < this.MyNumbers.Length; i++) { this.MyNumbers[i] = -1; } } } class Program { static void Main(string[] args) { MyGlobals globVariable = new MyGlobals(); globVariable.GetParam(); long n = globVariable.TotNum; Console.WriteLine("Fib ({0}) = {1}", n, Fibonacci(n)); Console.ReadKey(); } static long Fibonacci(long n) { MyGlobals globVariable = new MyGlobals(); if (n <= 1) { return 1; } if (globVariable.MyNumbers[n] != -1) { return globVariable.MyNumbers[n]; } else { globVariable.MyNumbers[n] = Fibonacci(n - 1) + Fibonacci(n - 2); } return globVariable.MyNumbers[n]; } } I'm trying to do something like feed an array by -1 in MyGlobals class for further using MyNumbers array in Fibonacci static method. Until line where I'm starting to call recursive fibonacci method it holds MyNumbers array in memory. But in Fibonacci method, when I create new instance of MyGlobals class for calling MyNumbers array is this array empty... What I'm doing wrong. Can you anybody help me on this, please. Thank you very much in forward.
Declare globVariable as a static member of the Program class like so: class Program { static MyGlobals globVariable = new MyGlobals(); static void Main(string[] args) { globVariable.GetParam(); long n = globVariable.TotNum; Console.WriteLine("Fib ({0}) = {1}", n, Fibonacci(n)); Console.ReadKey(); } static long Fibonacci(long n) { if (n <= 1) { return 1; } if (globVariable.MyNumbers[n] != -1) { return globVariable.MyNumbers[n]; } else { globVariable.MyNumbers[n] = Fibonacci(n - 1) + Fibonacci(n - 2); } return globVariable.MyNumbers[n]; } }
There is no such thing as global variables in C#. The problem you're having relates to instances of nonstatic classes. You effectively have three separate units in your code: One class that asks for input, holds this input and holds an array of result variables (MyGlobals). This is in fact way too much for a single class and should ultimately be split up. One method that calculates Fibonacci numbers and stores them into the previous class (Fibonacci). A Program class and Main() method which host your console application. Now your problem is that you don't know how to access the array of inputs stored in 1 from method 2. There are various ways to solve that, each with their own cons and pros. The most obvious one is to pass a reference. But before that, clean up your code: give classes and methods meaningful names, and extract logic into separate classes. Here you'll remain with three classes: public class FibonacciInput { public void GetParam() { // Your "MyGlobals" logic } } Then the calculation logic: public class FibonacciCalculator { public long Fibonacci(long index, long[] range) { // Your "Fibonacci()" logic } } And the program: class Program { static void Main(string[] args) { FibonacciInput input = new FibonacciInput(); FibonacciCalculator calculator = new FibonacciCalculator(); input.GetParam(); long n = input.TotNum; Console.WriteLine("Fib ({0}) = {1}", n, calculator.Fibonacci(n, input.MyNumbers)); Console.ReadKey(); } } Now your calculator doesn't know anything about your input, and the need for "global variables" goes away. The point is that the Fibonacci() method needs two things: the index (the Nth Fibonacci number it should calculate) and an array to work with (which you initialized on beforehand). So by calling calculator.Fibonacci(n, input.MyNumbers), you solve all problems at once.
Well, may be it's not really answers your question but i'd refactor your code dividing it to logical parts where each part is only responsible for one thing : UI Global variables Class that knows how to work with fibo sequence Program (entry point) Refactored code may look something among the lines of : // Globals should be static public static class MyGlobals { public static long TotNum { get; private set; } public static long[] MyNumbers { get; private set; } public static void SetNum(long num) { TotNum = num; MyNumbers = new long[TotNum + 1]; } } // interacts with UI public static class UIHelper { public static long GetParam() { Console.Write("n = "); var number = long.Parse(Console.ReadLine()); return number; } } // Knows how to calc fibo static class Fibo { static long Calc(long[] nums, long n) { ... calc fibonacci logic } } class Program { static void Main(string[] args) { // now we can use them all // first lets get value from console var num = UIHelper.GetParam(); // set global variables with this value MyGlobals.SetNum(num); // output result : Console.WriteLine("Fib ({0}) = {1}", n, Fibo.Calc(MyGlobals.MyNumbers, MyGlobals.TotalNum)); Console.ReadKey(); } } P.S. Whether to send global values as parameters to Fibo.Calc() method or to access them directly from inside of it it's up to you. I vote for first option because it makes it easier to test this method by passing mock data.
Generate list with random numbers. Sort and total sum
I am new to programming and i would be delighted if someone could help me with the following problem. I have problem with two methods. First sum all of 50 random numbers in a list, second sort list with 50 random numbers. I know how to do this when a list has for example four numbers{1,2,3,8} , but not with 50 random numbers. It will be nice to use a constructor to this two methods, but I don't now how to do this. Any help would be much appreciated. class Class1 { var rand = new Random(); public Class1( ) // how to use a constructor ? public static List<double> TotalSum() { var alist = new List<double>(); for (int i = 0; i < 50; i++) { alist.Add(rand.Next(10)); } Console.WriteLine("Total sum:", alist); } public static List<double> Sort() { var slist = new List<double>(); for (int i = 0; i < 50; i++) { slist.Sort(rand.Next(10)); // rand.Next does not work with Sort Console.WriteLine(slist); } } class Program { static void Main(string[] args) { Class1 show = new Class1(); show.TotalSum(); show.Sort(); } } }
just use the 2 methods list.Sum(); list.Sort(); I suggest that you use rand.Next(Environment.TickCount) to get better random numbers, but at the end you need to use a different primitive value to store the result class Program { static void Main(string[] args) { var array = Class1.Sort(); PrintArray(array); Console.WriteLine(); Console.WriteLine("Total sum: {0}", Class1.TotalSum()); Console.ReadLine(); } static void PrintArray(List<double> array) { foreach (var a in array) Console.WriteLine(a); } } public class Class1 { public static double TotalSum() { var rand = new Random(); var alist = new List<double>(); for (int i = 0; i < 50; i++) { alist.Add(rand.Next(10)); } return alist.Sum(); } public static List<double> Sort() { var rand = new Random(); var slist = new List<double>(); for (int i = 0; i < 50; i++) { slist.Add(rand.Next(10)); // rand.Next does not work with Sort } slist.Sort(); return slist; } }
I think I got what you mean. You want a class that holds random list of numbers and you need some functions. Its better to give more suitable name to your class. for example "RandomList" would be good. You can't use Console.WriteLine(list) to print items of list. You have to iterate through items and print them in the way you want. You can't use var to define fields. You have to write the type explicitly. static keyword in other word is one for all instances. So if you dont use static it would be one per instance. Instance is just the object that you create with the constructor. Its better to declare random number generator as static, but other methods and list field should remain non static. With the use of Linq Sum() you can get the sum of all the items from list. If you dont want to use Linq then you have to iterate through list and add each item to value sum. I commented the code to explain things. class Program { static void Main(string[] args) { RandomList show = new RandomList(50, 10); show.TotalSum(); show.Sort(); } } class RandomList { private static Random rand = new Random(); private List<double> _list; // this field holds your list public RandomList(int length , int maxValuePerItem) // this is the constructor { _list = new List<double>(); // populate list for (int i = 0; i < length; i++) { _list.Add(rand.Next(maxValuePerItem)); } } public void TotalSum() { Console.WriteLine("Total sum: {0}", _list.Sum()); // {0} is required to specify the place to put _list.Sum() inside string. // without linq way // int sum = 0; // foreach(var i in _list) sum += i; } public void Sort() { _list.Sort(); foreach (var d in _list) { Console.Write(d + " , "); // you need to print this in the way you want. } } }
A constructor is typically used to initialize some values. In your case, you should use it to initialize your list, that is, to load it with 50 random numbers. We will also change it so that the list is a property of the class. Note that the methods shouldn't be static, since they are acting on a property of the class. We are also using the built-in methods of List (Sum() and Sort()) instead of rolling our own. class Class1 { var rand = new Random(); var alist; public Class1() // constructor creates a new list and initializes it { alist = new List<double>(); for (int i = 0; i < 50; i++) { alist.Add(rand.Next(10)); } } public List<double> TotalSum() { Console.WriteLine("Total sum:", alist.Sum()); } public List<double> Sort() { alist.Sort(); for (double num in alist) { Console.WriteLine(num.ToString()); } } class Program { static void Main(string[] args) { Class1 show = new Class1(); show.TotalSum(); show.Sort(); } } }
Because you asked how to use the constructor I tried to rewrite your code in a way that the constructor do something of usefull. I added a property and a local variable plus another function. public class Class1 { Random rand = new Random(); List<double> alist { get; set; } public Class1(int howmany = 50) { alist = new List<double>(); for (var i = 0; i < howmany; i++) { alist.Add(rand.NextDouble()); } } public void Sort() { alist.Sort(); } public void printTotalSum() { Console.WriteLine("Total sum: {0}", alist.Sum()); } public void printList() { Console.WriteLine("The list contains:"); for (int i = 0; i < alist.Count; i++) { Console.WriteLine(alist[i]); } } } class Program { static void Main(string[] args) { Class1 show = new Class1(10); show.printTotalSum(); show.Sort(); show.printList(); } }