So this is the Program cs. I want to change the value of int in my StaticClass.cs ** I want to delcare a printing sentence " How long do you want me to generate " then change the value of N in StaticClass.
class Program
{
static void Main(string[] args)
{
Constructor ct = new Constructor(StaticClass.n);
//ct.xmethod(StaticClass.n);
Console.ReadKey();
}
}
Here my constructor class. Method of Pascal Triangle
class Constructor
{
int[][] triangle = new int[StaticClass.n][];
public Constructor(int n)
{
xmethod(n);
}
public void xmethod(int n)
{
for (int row = 0; row < triangle.Length; row++)
{
//Each row is a subarray of length 1 greater than row number
triangle[row] = new int[row + 1];
//set the values in a row
for (int k = 0; k < triangle[row].Length; k++)
{
// if not first or last element in the row
if (k > 0 & k < triangle[row].Length - 1)
//set it to sum of the element above it
//and the one above and to the left
triangle[row][k] = triangle[row - 1][k - 1] + triangle[row - 1][k];
//otherwise this is an end point, set it to 1
else
triangle[row][k] = 1;
//display value
Console.Write(triangle[row][k] + "\t");
}
// Finished processing row-send cursor to next line
Console.WriteLine();
}
}
}
Here my StaticClass for the long of Pascal Triangle
class StaticClass
{
public const int n = 15;
// I want to change the value of N using the Console Writeline.
}
n needs to be updatable then instead of const use static; but Console.WriteLine() is not something you would use to change the value. You'll need to be more clear about what you want to do. Do you want someone to input the value of n - with a Console.ReadLine?
So ... from what I gather -- I think you want to change your Main to write your question: " How long do you want me to generate " then read the line for user input. Then print your triangle. Something like :
static void Main(string[] args)
{
Console.WriteLine("How long do you want me to generate? ");
int inNum = int.Parse(Console.ReadLine());
Constructor ct = new Constructor(inNum);
Console.ReadKey();
}
Then from what I see ... your Constructor needs to change:
public Constructor(int n)
{
triangle = new int[n][];
xmethod(n);
}
You cannot change the value of a const. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants
Use a static property instead.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
static class StaticClass
{
public static int n = 15;
// I want to change the value of N using the Console Writeline.
}
Make your public const field a public static property instead:
public static int N { get; set; } = 15;
Change it like
StaticClass.N = 16;
You said "change it with WriteLine" - WriteLine outputs things, it doesn't change thing. Perhaps you meant ReadLine:
Console.WriteLine("How many levels? ");
string input = Console.ReadLine();
StaticClass.N = int.Parse(input);
Do please find a better name for StaticClass; classes should be named for what they represent in a more real world sense (like.. Configuration?) not what they are in a C# sense (yes, it's a static class, but it doesn't mean we should call it that)
Related
I'm a new to C#, please give me some advice on my program. How to pass a value from a method to another method? I am trying to do a calculation by using the value n from part_number in another method.
class Program
{
static void Main(string[] args)
{
int n;
part_number(out n);
Athlete myobj = new Athlete();
int n1 = 0;
for (n1 = 0; n1 < n; ++n1)
{
Write("Enter your participant name >> ");
myobj.participant_Name = ReadLine();
WriteLine("Event codes are:");
WriteLine("T Tennis");
WriteLine("B Badminton");
WriteLine("S Swimming");
WriteLine("R Running");
WriteLine("O Other");
Write("Enter event code>> ");
myobj.event_Code0 = ReadLine();
}
double totalCost;
const double cost = 30.00;
totalCost = cost * n1;
WriteLine("The total cost is {0}", totalCost);
static void part_number(out int n)
{
n = 0;
WriteLine("Enter the number the participant this year>> ");
n = System.Convert.ToInt32(ReadLine());
while (n >= 40)
{
WriteLine("Please enter number between 0 to 40");
n = System.Convert.ToInt32(ReadLine());
}
}
}
How to pass the value of n from part_number method and another method? I need to the use that value to do a calculation in another method. Should I build a class for it?
Thank you!
You would simply add an argument to the method such as:
void MyOtherMethod(int number)
{
// do something with number
}
If you wanted, you could pass multiple things by commad delimiting them:
void MyOtherMethod(int number, string name)
{
}
You can also have a method returning a value:
int MyReturningMethod(int number)
{
return number + 2;
}
The possibilities are endless.
You will have to call your other method and pass it in.
public static Main(string[] args)
{
PartNumer(out var partNumber);
OtherMethod(partNumber);
}
static void PartNumber(out int pn)
{
pn =1;
}
static void OtherMehtod(int partNumber)
{
Console.WriteLine($"Your part number is {partNumber}");
}
I am trying to write an array to a file with C# and am having issues.
I've started learning c# the last few days and now can't figure out why this happens.
namespace Arrays
{
class Program
{
static void Sort()
{
}
public static void Random()
{
int[] test2 = new int[5];
int Min = 1;
int Max = 100;
Random randNum = new Random();
for (int i = 0; i < test2.Length; i++)
{
test2[i] = randNum.Next(Min, Max);
Console.WriteLine(test2[i]);
}
Console.WriteLine("");
for (int ii = 0; ii < test2.Length; ii++)
{
Array.Sort(test2);
Console.WriteLine(test2[ii]);
}
String writeToText = string.Format("{0}", test2);
System.IO.File.WriteAllText(#"C:\\Users\\hughesa3\\Desktop\\log.txt", writeToText); // Writes string to text file
}
static void Main(string[] args)
{
Random();
}
}
}
It generates a random 5 numbers and puts it into the array, When I try to write this to a file it prints System.Int32[]
I understand that because im trying to print a formated string but how would i go about printing each int ? I've tried using a loop but it will only save the last int as i put it inside the loop?
Can anyone give me some advice ?
Thanks
Use WriteAllLines and pass string array as input.
System.IO.File.WriteAllLines("filename", test2.Select(i=>i.ToString()).ToArray());
or, if you want to write in , separated form use this.
System.IO.File.WriteAllText("filename", string.Join(",", test2.Select(i=>i.ToString()).ToArray());
The problem is that String writeToText = string.Format("{0}", test2); calls ToString method of the test2 array and it returns System.Int32[]
Change it to
String writeToText = string.Join("", test2.Select(x=>x.ToString())
or
String writeToText = string.Format("{0}", test2.Select(x=>x.ToString().Aggregate((c,n)=>string.Format("{0}{1}", c,n))
//Add this method and use in System.IO.File.WriteAllText(#"C:\\Users\\hughesa3\\Desktop\\log.txt", ArrayToString(test2));
public static String ArrayToString(int[] arr)
{
return arr.Aggregate("", (current, num) => current + (num + " "));
}
I can't seem to figure out how to fix my code so that it works. I need the user to be able to input their first name then space then the what they scored. Then I need to split the array into two different arrays and pass them to the four different methods to display to the user what they scored, etc. Can anyone help me figure this problem out?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace proj09LEA
{
class Program
{
static void Main(string[] args)
{
// declare and array of integers
int[] array = new int[10];
Console.WriteLine("\nSaturday Coder's Bowling Team");
Console.WriteLine("Enter in a name and score for each person on the team.");
Console.WriteLine("For example, Mary 143. Just hit Enter when you are done.\n");
// fill an array with user input
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter in a name and score: ");
string userInput;
string[] parsedInput;
parsedInput = userInput.Split();
string name = parsedInput[0];
int score = int.Parse(parsedInput[1]);
}
Console.WriteLine("------------ Input Complete ------------\n");
Console.WriteLine("Here are the scores for this game:");
DisplayScore(array);
HighScore(array);
LowScore(array);
AverageScore(array);
Console.WriteLine("Press Enter to continue. . .");
Console.ReadLine();
}
static void DisplayScore(int[] array)
{
foreach (int n in array)
{
Console.WriteLine("{0}'s score was {0}.\n", array);
}
}
static void HighScore(int[] array)
{
int max = array.Max();
Console.WriteLine("Congratulations {0}, your score of {0} was the highest.", max);
}
static void LowScore(int[] array)
{
int min = array.Min();
Console.WriteLine("{0}, your score of {0} was the lowest. Better get some practice.", min);
}
static void AverageScore(int[] array)
{
int sum = array.Sum();
int average = sum / array.Length;
Console.WriteLine("The average score for this game was {0:d}.", average);
}
}
}
If you absolutely have to use simple primitive arrays, you would need two distinct arrays of the same size, to hold the names as strings and scores as ints:
class Program
{
const int MaxScores = 10; // .. Use a constant to ensure the sizes remain in sync
static void Main(string[] args)
{ ///
string[] names = new int[MaxScores];
int[] scores = new int[MaxScores];
// ... parse names into names[] and scores into scores[]
DisplayScore(names, scores);
You would then need to pass both arrays to the various methods:
static void DisplayScore(string[] names, int[] scores)
{
for(int i=0; i < MaxScores; i++)
{
Console.WriteLine("{0}'s score was {1}.\n", names[i], scores[i]);
}
}
// etc
However, there are better ways to do this, e.g. by defining a custom class for the tuple of Name, Score:
class PersonScore
{
public string Name {get; set;}
public int Score {get; set;}
}
You can then declare and pass the single array of PersonScore[] around.
PersonScore[] personScores = new PersonScore[MaxScores];
for (... prompting the user for data)
{
... parsing user input
personScores[i] = new PersonScore{Name = name, Score = score};
}
DisplayScore(personScores); // Pass around the single array
static void DisplayScore(IEnumerable personScores)
{
foreach(var personScore in personScores)
{
Console.WriteLine("{0}'s score was {1}.\n", personScore.Name, personScores.Score);
}
}
// etc - other methods
As others have mentioned, other collections are also possible alternatives to an array, most commonly List.
You can do like this. Just use Console.ReadLine() to get user input. This is what you do in your code. There are better ways to do this but following will solve your problem.Also you need to perform validation as well.
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter in a name and score: ");
string userInput = Console.ReadLine();
string[] parsedInput;
parsedInput = userInput.Split(' ');
string name = parsedInput[0];
int score = int.Parse(parsedInput[1]);
array[i] = score;
}
Why you need to split array in to two arrays on containing names and other containing score. Its better to create a structure having String field for name and integer field for score and write Comparator for sorting the Array containing elements of this Data structure type and sort them.
It will solve all your problems and that too efficiently.
Not many data integrity checks in the methods you are using, but here are the extensions I use to split arrays or any type of enumerable. I have not tested these all that much, so I cannot guarantee that they will work. I have removed all my input validation, but I suggest you add those back your own way.
public static List<List<T>> Split<T>(this IEnumerable<T> collection, Int32 groupSize)
{
var collectionList = collection.ToList();
if (groupSize > collectionList.Count)
groupSize = collectionList.Count;
var chunks = new List<List<T>>();
while (collectionList.Any())
{
var chunk = collectionList.Take(groupSize);
chunks.Add(chunk.ToList());
collectionList = collectionList.Skip(groupSize).ToList();
}
return chunks;
}
public static List<List<T>> Split<T>(this IEnumerable<T> collection, Func<T, Boolean> splitFunction)
{
var collectionList = collection.ToList();
if (collectionList.IsNullOrEmpty())
return new List<List<T>>();
var indices = collectionList.FindIndices(splitFunction); // Custom method that searches for the indices that satisfy the predicate and returns the index of each matching item in the list.
if (indices.IsNullOrEmpty()) // equivalent to indices == null || !indices.Any()
return new List<List<T>> { collectionList };
var chunks = new List<List<T>>();
var lastIndex = 0;
if (indices[0] > 0)
{
chunks.Add(collectionList.Take(indices[0]).ToList());
lastIndex = indices[0];
}
for (var i = 1; i < indices.Count; i++)
{
var chunkSize = indices[i] - lastIndex;
var chunk = collectionList.Skip(lastIndex).Take(chunkSize).ToList();
if (chunk.IsNullOrEmpty())
{
break;
}
chunks.Add(chunk);
lastIndex = indices[i];
}
if (collectionList.Count - lastIndex > 0)
{
var lastChunk = collectionList.Skip(lastIndex).ToList();
chunks.Add(lastChunk);
}
return chunks;
}
Just a very quick question.
I have a classe called "Mezo.cs" that is basically a 'public int[,]'.
A specific copy of this class is a int[,] containing 1 or 0.
I want to find the 1s.
So in the main program I iterate through it with fors but i get the error in the title.
Any help would be appreciated.
static void WriteShips(Mezo mezo, StreamWriter SW)
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (mezo[i, j] == 1)
{
SW.WriteLine(i.ToString(), j.ToString());
}
}
}
}
This is in a battleship program where I want to basically want to save the coordinates of the ships in a txt.
mezo[i, j] gives the error
MEZO CLASS:
class Mezo
{
public int[,] mezo;
public Mezo() // KONSTRUKTOR
{
mezo = new int[10, 10];
kitoltesUressel();
}
kitoltesUressel() is irrelevant, it just randomly fills the copy with 1s and 0s.
In order to use an instance of your class with indexes (pretty much like any collection in the framework), you need to have a property that will act like the index manager.
Here is a simple code of a class that behaves like an array:
public class MyIndexedClass
{
private string[] _values = new string[]
{
"hello",
"hi",
"good morning",
"long time no see"
};
public string this[int index]
{
get
{
Console.WriteLine("Index called with argument value " + index);
return _values[index];
}
set
{
Console.WriteLine("Index called with argument value " + index + " and value " + value );
_values[index] = value;
}
}
}
In my example, using the code myIndexedClassInstance[0]; returns a string containing "hello".
I'm guessing your "Mezo" class contains a jagged array inside of it, but not using the "this" keyword.
You can check more about indexes here.
EDIT:
Updated now given the new info about your Mezo class, the code that is giving you the error should look like this:
if (mezo.mezo[i, j] == 1)
{
SW.WriteLine(i.ToString(), j.ToString());
}
Because you are passing an instance of Mezo, which is the one containing the array called mezo.
You cannot use the instance of the class itself as if it was the jagged array property.
i have done coding in C# but not much inside the Console App (teacher is making us do an assignment in it)
I have a problem where my static method works fine the first time it is called (each question is asked), but the second time through the console closes. I need this function to execute 10 times and not sure why it wont. Here is what i have and thanks in advance!:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab2
{
class Program
{
//Create the arrays
static string[] questions = new string[5]; //For questions
static int[] tableHeader = new int[10]; //Table Header
static int[,] responses = new int[5, 10]; //For answers
//Int for the number of times the questions have been asked
static int quizCount = 0;
static int answer;
static bool isGoing = true;
static void Main(string[] args)
{
//Set the questions in an array
questions[0] = "On a scale of 1-10, how do you feel about the drinking age in Wisconsin?";
questions[1] = "On a scale of 1-10, how often do you drink a week?";
questions[2] = "On a scale of 1-10, how important is this class?";
questions[3] = "On a scale of 1-10, how would you rate this campus?";
questions[4] = "On a scale of 1-10, how would you rate this command prompt?";
while(isGoing)
Questions();
}
static void Questions()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(questions[i]);
answer = Convert.ToInt16(Console.ReadLine());
responses[i, quizCount] = answer;
}
if (quizCount < 10)
{
Console.WriteLine("Enter more data? (1=yes, 0=no)");
int again = Console.Read();
if (again != 1)
Environment.Exit(0);
}
else
isGoing = false;
DisplayResults();
}
static void DisplayResults()
{
Console.WriteLine(tableHeader);
for (int i = 0; i < 5; i++)
{
for (int x = 0; x < 10; x++)
{
Console.Write(responses[i, x]);
}
Console.Write("\n");
}
}
}
}
First off Console.Read() returns an int representing the ascii value of what was entered. If the user enters 1, Console.Read() returns 49. (See this ascii table)
You could use Console.ReadKey()
Second, you need some fixes in the way you loop and ask to continue....
int again = Console.Read();
Your problem is here - Console.Read() returns the first character entered (as represented by its ASCII code), not the number you type in. I leave the solution for your homework.