Visual studio C# Invisible Friend Game code - c#

I've been trying how to make the couples, what I have to do is develop a program(console app) where I have to
Add players(max 30)
Mix those players between then(every name has to appear in each column once
For example:
The partner of Maria is Juan, therefore Maria has to give the gift to Juan, each person has to appear once on each side. I've tried 2 codes:
Code 1:
Console.WriteLine("Bienvenido al juego del amigo invisible!");
string[] nombres= new string[30];
bool salir = false;
int personas=30 ;
int cant = 1;
while (salir != true)
{
int opc;
Console.WriteLine("1-Introducir parejas 2-Amigo invisible 3-Introducir parejas 4- Añadir más personas 5-Salir ");
while (!int.TryParse(Console.ReadLine(), out opc))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
switch (opc)
{
case 1:
Nombres(ref nombres, ref personas);
break;
case 2:
Parejas(nombres,ref personas);
break;
case 3:
Parejitas(cant);
break;
case 4:
MasParejas(ref personas);
break;
case 5:
salir = true;
break;
}
}
static void Nombres(ref string[] nombres, ref int personas)
{
Console.WriteLine("Cuantas personas sois");
while (!int.TryParse(Console.ReadLine(), out personas))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
nombres = new string[personas];
Console.WriteLine("introduzca" + personas + "nombres");
for (int a = 0; a < personas; ++a)
{
nombres[a] = Console.ReadLine();
}
for (int a = 0; a >= personas;)
{
Console.WriteLine("Las personas que jugaran contigo serán:" + nombres[a]);
}
Console.Clear();
}
static void Parejas(string[] nombres, ref int personas)
{
Random rnd = new Random();
bool aprobado = false;
int[] usados = new int[personas];
Console.WriteLine("Hagamos las parjeas");
foreach (string persons in nombres)
{
do
{
for (int i = 0; i < personas; i++)
{
int h = rnd.Next(0, personas - 1);
do
{
string name = nombres[h];
if (name != null)
{
if (persons?.CompareTo(name) != 0 && usados.Contains(h))
{
aprobado = true;
Console.WriteLine($"{nombres[i]} va con {nombres[h]}");
}
}
usados[i] = h;
} while ( usados.Contains(h));
}
} while (!aprobado);
}
}
static void Parejitas(int cant)
{
Console.WriteLine("Hagamos las parejas por separado.");
string[] parejitas = new string[cant];
do
{
if (cant % 2 != 0)
{
while (!int.TryParse(Console.ReadLine(), out cant))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
}
} while (cant % 2 != 0);
Console.WriteLine("Introduzca los nombres de las parejas");
for (int i = 0; i < cant; i++)
{
parejitas[i] = Console.ReadLine();
}
for (int i = 0; i < cant; i++)
{
Console.WriteLine($"las parejas son {parejitas[i]} con {parejitas[i + 1]}");
}
Console.Clear();
}
static void MasParejas(ref int personas)
{
int más;
Console.WriteLine("¿Cuanta gente quiere añadir?");
while (!int.TryParse(Console.ReadLine(), out más))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
int total = personas + más;
do
{
if (total >= 30 || más % 2 != 0)
{
Console.WriteLine("Ha superado el limite de personas o introducido un número inpar, el limite es 30");
while (!int.TryParse(Console.ReadLine(), out más))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
}
} while (total >= 30 || más % 2 != 0);
int a = 1;
string[] personasañadidas = new string[más];
Console.WriteLine("Introduzca los nombres de los nuevos");
for (int i = 0; i < más; i++)
{
personasañadidas[i] = Console.ReadLine();
}
for (int j = 0;j < personasañadidas.Length; j++)
{
if (j< personasañadidas.Length-1)
{
Console.WriteLine($" Parejas: {personasañadidas[j]} con {personasañadidas[j + 1]}");
}
if (j==personasañadidas.Length-1)
{
Console.WriteLine($" Parejas: {personasañadidas[j]} con {personasañadidas[0]}");
}
}
}
Code 2:
static void Main(string[] args)
{
bool salir = false;
int cantidadPersonas=30 ;
string[] Personas = new string[cantidadPersonas];
while (salir != true)
{
int opc;
Console.WriteLine("1-Introducir parejas 2-Amigo invisible 3-Salir ");
while (!int.TryParse(Console.ReadLine(), out opc))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
switch (opc)
{
case 1:
MeterNombres(ref cantidadPersonas, ref Personas);
break;
case 2:
GenerarParejas(cantidadPersonas, Personas);
break;
case 3:
salir = true;
break;
}
}
static void MeterNombres(ref int cantidadPersonas, ref string[] Personas) {
Console.WriteLine("¿Cuantos sois?");
cantidadPersonas = Convert.ToInt32(Console.ReadLine());
do
{
if (cantidadPersonas % 2 != 0)
{
cantidadPersonas = Convert.ToInt32(Console.ReadLine());
}
} while (cantidadPersonas % 2 != 0);
Console.WriteLine("Introduzca los nombres de las personas que vayan a participar:");
for (int i = 0; i < cantidadPersonas; i++)
{
Personas[i]= Console.ReadLine();
}
Console.Clear();
Console.WriteLine("Los participantes son:");
for (int i = 0; i < cantidadPersonas; i++)
{
Console.WriteLine(Personas[i]);
}
}
static void GenerarParejas(int cantidadPersonas, string[] Personas)
{
Console.WriteLine("Comencemos a generar las parejas...");
string[] PersonasCopia = new string[cantidadPersonas];
Random rnd = new Random();
bool Repeticiones = false;
int NumeroAleatorio;
for (int i = 0; i < cantidadPersonas; i++)
{
PersonasCopia[i] = Personas[i];
}
for (int i = 0; i < cantidadPersonas; i++)
{
do
{
Repeticiones = false;
NumeroAleatorio = rnd.Next(0, cantidadPersonas);
if (Personas[i] == PersonasCopia[i])
{
Repeticiones = true;
}
} while (Repeticiones = false); ;
}
}

Related

c# how to fill an array with user input

I'm creating a lottery program that users can choose from a series of numbers between a particular range and the program then creates its own version of numbers and compares those user values against the program's random numbers which any matches that the program then finds are then displayed to the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assessment1.Lottery
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please insert 6 lottery numbers:");
int range = 100;
int minValue = 0;
int maxValue = 100;
int a = 0;
Random rnd = new Random();
int[] myArray = new int[6];
for ( int i=0; i < myArray.Length; i++ )
{
int randomNumber = rnd.Next(minValue, maxValue);
myArray[i] = randomNumber;
Console.WriteLine(randomNumber);
myArray[i] = int.Parse(Console.ReadLine());
Console.WriteLine(myArray[i]);
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out myArray[a]))
a++;
else
Console.WriteLine("invalid integer");
}
double arry = myArray.Average();
if(arry > 0)
Console.WriteLine("found");
else
Console.WriteLine("not found");
int BinarySearch(int[] array, int value, int low, int high)
{
if ( high >= low)
{
int mid = (low + high) / 2;
if (array[mid] == value) return mid;
if (array[mid] == value) return BinarySearch(array, value, low, mid - 1);
return BinarySearch(array, value, mid + 1, high);
}
return -1;
}
}
Console.ReadLine();
}
}
}
when I run the program it shows the following
Please insert 6 lottery numbers: 64
how can I fix this so that the array can be filled with user input
Here is a version of something I wrote a while back and modified to your parameters, if there are bugs please don't ask me to fix.
static void Main(string[] args)
{
int stop = 0;
int[] chosenNum = new int[6];
while (stop == 0)
{
Console.Clear();
string con = "";
Console.WriteLine("Enter six numbers between 1-100 separated by a comma with no duplicates:");
string numbers = Console.ReadLine();
string[] userNumbers = numbers.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToArray();;//remove ex: ,, issues
string[] checkDup = userNumbers.Distinct().ToArray();//remove duplicates
if (userNumbers.Count() < 6)
{
Console.WriteLine("You entered less than six numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (userNumbers.Count() > 6)
{
Console.WriteLine("You entered more than 6 numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (checkDup.Count() < 6)
{
Console.WriteLine("You entered duplicate numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (!isNumeric(userNumbers))
{
Console.WriteLine("You entered non-numeric value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (isInRange(userNumbers) < 6)
{
Console.WriteLine("You entered out of range value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else
{
var lowerBound = 1;
var upperBound = 100;
var random = new Random();
int[] randomNum = new int[6];
int count = 0;
foreach(string str in userNumbers){
var rNum = random.Next(lowerBound, upperBound);
randomNum[count] = rNum;
count++;
}
string[] ourPicks = Array.ConvertAll(randomNum, s => s.ToString()).ToArray();
Array.Sort(userNumbers);
Array.Sort(ourPicks);
//string[] ourpicks = { "1", "2" };//for testing
Console.WriteLine("Your Numbers: {0}", string.Join(", ", userNumbers));
Console.WriteLine("Our Numbers: {0}", string.Join(", ", ourPicks));
string[] result = userNumbers.Intersect(ourPicks).ToArray();
if(result.Count() > 0)
{
Console.WriteLine("Matchs: {0}", string.Join(", ", result));
}
else
{
Console.WriteLine("Match's = 0");
}
stop = 1;
}
}
Console.ReadLine();
}
public static bool isNumeric(string[] num)
{
foreach (string str in num)
{
bool check = int.TryParse(str, out int test);
if (!check)
{
return false;
}
}
return true;
}
public static int isInRange(string[] num)
{
int count = 0;
foreach (string str in num)
{
int.TryParse(str, out int test);
if (test > 0 & test <= 100)
{
count++;
}
}
return count;
}

My WindowsForm just ignore some code lines and I don't know why?

I've been programming a soft on VS in C#. It is an old program made by someone else by me but my problem is in my code I think. In this soft, there is two Form, the 1st one get some datas, and the second make the operations and also provide a report of the datas that I use.
double sum = 0;
for (int k = 0; k <= length - 1; )
{
sum += Convert.ToDouble(pisteA[k]);
k += 1;
}
double average = sum / 3;
I have an array containing Text and null values in the 2nd Form. I just want to make an average of this array, so with a for loop, I did what I have to do. But, when I launch my soft, It doesn't go through the line code and stops at this line.
sum += Convert.ToDouble(pisteA[k]);
When I use the Breakpoint to see what's happening, the code go through this line, and then go to my other form to execute this :
formImpression.Show();
To test something, I added a MessageBox.Show just after the line of the sum, and also before, and it seems that the soft execute the code above the problem line, but not the ones that are after this.
I seriously don't have any idea of what's happening.
Edit : For more comprehension about the code I use, I leave it here.
String[] varGen = { formulaire.Form1.varG.piste1, formulaire.Form1.varG.piste2, formulaire.Form1.varG.piste3, formulaire.Form1.varG.piste4, formulaire.Form1.varG.modulesPiste1, formulaire.Form1.varG.modulesPiste2, formulaire.Form1.varG.modulesPiste3, formulaire.Form1.varG.modulesPiste4 };
TextBox[] pisteA = { mesure1, mesure2, mesure3, mesure4, mesure5, mesure6, moyenne1 };
TextBox[] pisteB = { mesure7, mesure8, mesure9, mesure10, mesure11, mesure12, moyenne2 };
TextBox[] pisteC = { mesure13, mesure14, mesure15, mesure16, mesure17, mesure18, moyenne3 };
TextBox[] pisteD = { mesure19, mesure20, mesure21, mesure22, mesure23, mesure24, moyenne4 };
double moyenne = 0;
int indexMesures = 0;
bool presencepn = false;
for (int n = 0; n < dataGridView1.Rows.Count; n++)
{
if (formulaire.Form1.varG.pn == dataGridView1.Rows[n].Cells[0].Value.ToString() & formulaire.Form1.varG.pn != null)
{
presencepn = true;
//Initialisation
object module_A1 = dataGridView1.Rows[n].Cells[1].Value;
object module_A2 = dataGridView1.Rows[n + 1].Cells[1].Value;
object module_A3 = dataGridView1.Rows[n + 2].Cells[1].Value;
object module_D1 = dataGridView1.Rows[n].Cells[2].Value;
object module_D2 = dataGridView1.Rows[n + 1].Cells[2].Value;
object module_D3 = dataGridView1.Rows[n + 2].Cells[2].Value;
int moduleA1 = int.Parse(module_A1.ToString())-1;
int moduleA2 = int.Parse(module_A2.ToString())-1;
int moduleA3 = int.Parse(module_A3.ToString())-1;
int moduleD1 = int.Parse(module_D1.ToString())-1;
int moduleD2 = int.Parse(module_D2.ToString())-1;
int moduleD3 = int.Parse(module_D3.ToString())-1;
//Remplissage tableau sans exclusion
// Piste [1,2,3,4]
for (int j = 0; j < formulaire.Form1.varG.nbPistes; j++)
{
// Initialisation de la moyenne
moyenne = 0;
// Valeur pour la piste J
for (int i = 0; i < Convert.ToInt32(varGen[j + 4]); i++)
{
// Calcul de la moyenne
moyenne = moyenne + mesures[indexMesures];
// Choix de la piste
if (varGen[j] == "A")
{
pisteA[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
}
else if (varGen[j] == "B")
{
pisteB[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
pisteB[6].Text = Math.Round((moyenne / Convert.ToDouble(varGen[j + 4])), 3).ToString(); // Remplissage de la case moyenne
}
else if (varGen[j] == "C")
{
pisteC[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
pisteC[6].Text = Math.Round((moyenne / Convert.ToDouble(varGen[j + 4])), 3).ToString(); // Remplissage de la case moyenne
}
else if (varGen[j] == "D")
{
pisteD[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
pisteD[6].Text = Math.Round(moyenne / Convert.ToDouble(varGen[j + 4]), 3).ToString(); // Remplissage de la case moyenne
}
// Incrémentation de l'index des mesures
indexMesures += 1;
}
}
int length = pisteA.Length - 1;
//Suppression des modules exclus
for (int k = 0; k <= length; k++)
{
if (k == (moduleA1) | k == (moduleA2) | k == (moduleA3))
{
pisteA[k].Text = null;
}
}
for (int k = 0; k <= length; k++)
{
if (k == (moduleD1) | k == (moduleD2) | k == (moduleD3))
{
pisteD[k].Text = null;
}
}
double sum = 0;
for (int k = 0; k <= length - 1; )
{
sum += Convert.ToDouble(pisteA[k]);
k += 1;
}
double moyA = sum / 3;
pisteA[6].Text = Math.Round(moyA).ToString();
}
Have you this setting checked to see exception ?

C#: cannot convert string to string [] []

I have a question regarding my code. The situation is the following: I am working with many arrays with data, all of same length. Then I want to build a second version with specific camps.
I have the following code:
string[][][] cuentasHFMPreFinal = new string[nroCuenta.Length][][];
string anoCubo = "'2019";
string escenarioCubo = "Control";
string versionCubo = "Version Vigente";
for (int i = 0, j = 0, k = 0; i < nroCuenta.Length && j < nroCuenta.Length && k < nroCuenta.Length; i++, j++, k++){
cuentasHFMPreFinal[i] = anoCubo;
}
The idea would be to give specific values to the new array (which will have more dimensions, this is a brief example). End array would end as something like:
cuentasHFM [anoCubo][escenarioCubo][versionCubo][....][lastVar]
The error is on the cuentasHFMPreFinal[i] = anoCubo part, giving the error on title.
Full code is:
static void Main(string[] args)
{
//-----------------------------------------------------------------------
//ARCHIVO CUENTAS AUTOMATICAS
//obtener direccion de archivo
string pathCuentasAuto = #"C:\DescargaHFM\data\cuentas_auto.txt";
pathCuentasAuto = Path.GetFullPath(pathCuentasAuto);
//leer lineas archivo y pasar a arreglo
string[] cuentasAuto = File.ReadAllLines(pathCuentasAuto);
//-----------------------------------------------------------------------
//ARCHIVO HFM CHILE
//obtener direccion de archivo
string pathHFM = #"C:\DescargaHFM\data\HFM.txt";
pathHFM = Path.GetFullPath(pathHFM);
//leer lineas archivo y pasar a arreglo
string[] hfm = File.ReadAllLines(pathHFM);
//obtener separador tab
string separadorTab = "\t";
//separar lineas por separadores
string[][] camposHFM = new string[hfm.Length][];
for (int i = 0; i < hfm.Length; i++) {
camposHFM[i] = hfm[i].Split(separadorTab.ToCharArray());
}
//arreglo con periodo(meses)
string[] mesesHFM = new string[camposHFM.Length];
for (int i = 0; i < camposHFM.Length; i++)
{
string mesPeriodo = camposHFM[i][0];
switch (mesPeriodo){
case "Per01":
mesPeriodo = "Jan";
break;
case "Per02":
mesPeriodo = "Feb";
break;
case "Per03":
mesPeriodo = "Mar";
break;
case "Per04":
mesPeriodo = "Apr";
break;
case "Per05":
mesPeriodo = "May";
break;
case "Per06":
mesPeriodo = "Jun";
break;
case "Per07":
mesPeriodo = "Jul";
break;
case "Per08":
mesPeriodo = "Aug";
break;
case "Per09":
mesPeriodo = "Sep";
break;
case "Per10":
mesPeriodo = "Oct";
break;
case "Per11":
mesPeriodo = "Nov";
break;
case "Per12":
mesPeriodo = "Dec";
break;
}
mesesHFM[i] = mesPeriodo;
}
//otener cantidad total y cantidad gl
double[] QTotalUSGAP = new double[hfm.Length];
double[] QTotalGL = new double[hfm.Length];
double[] QTotalResta = new double[hfm.Length];
for (int i = 0; i < camposHFM.Length; i++) {
QTotalUSGAP[i] = Double.Parse(camposHFM[i][3]);
QTotalGL[i] = Double.Parse(camposHFM[i][4]);
QTotalResta[i] = QTotalUSGAP[i] - QTotalGL[i];
}
//obtener numero cuenta
string[] nroCuenta = new string[hfm.Length];
/*Formula Excel:
*SI(IZQUIERDA(C2;4)="ACCT";MED(C2;5;LARGO(C2)-3);IZQUIERDA(C2;ENCONTRAR("_";C2)-1))
*/
for (int i = 0; i < camposHFM.Length; i++) {
nroCuenta[i] = camposHFM[i][2];
if (nroCuenta[i].Substring(0, 4) == "ACCT") {
nroCuenta[i] = nroCuenta[i].Substring(5, (nroCuenta[i].Length - 3));
}
else {
//int indexFind = nroCuenta[i].IndexOf('_');
//nroCuenta[i] = nroCuenta[i].Substring(0, (indexFind - 1));
nroCuenta[i] = nroCuenta[i].Substring(0, nroCuenta[i].Length);
}
}
//comprobar existencia de nroCuenta en cuentasAuto
string[] existeNroCuenta = new string[nroCuenta.Length];
for (int i = 0; i < nroCuenta.Length; i++){
if (cuentasAuto.Contains(nroCuenta[i])){
existeNroCuenta[i] = "TRUE";
}
else{
existeNroCuenta[i] = "FALSE";
}
}
//armar arreglo pre final
string[][][] cuentasHFMPreFinal = new string[nroCuenta.Length][][];
string anoCubo = "'2019";
string escenarioCubo = "Control";
string versionCubo = "Version Vigente";
string monedaCubo = "CLP";
string ubgCubo = "Generico UBG";
string ajusteICCubo = "Ajuste 99";
string organizacionCubo = "Generico";
for (int i = 0, j = 0, k = 0; i < nroCuenta.Length && j < nroCuenta.Length && k < nroCuenta.Length; i++, j++, k++){
cuentasHFMPreFinal[i] = anoCubo;
}
}
Use classes, structs or tuples to achieve what you're trying to achieve.

Outside Bounds of Array When Reading From File

I'm new to C# - I've got a 'Treasure Hunt' game here - it hides a 't' in a box, then the user inputs coordinates - if they get 't' it says they've won, if not then a 'm' is displayed.
I'm trying to setup save games linked to the name a user enters. It writes the save game to a txt file and stores it - that much works. But when I try to load the game I keep getting an error 'Index was outside the bounds of the array'.
static string username = "";
static string saveGame = "";
public const int BoardSize = 10;
static void Main(string[] args)
{
char[,] Board = new char[10, 10];
Console.WriteLine("Would you like to:");
Console.WriteLine("1. Start New Game");
Console.WriteLine("2. Load Game");
Console.WriteLine("9 Quit.");
int mainMenuChoice = 0;
mainMenuChoice = int.Parse(Console.ReadLine());
if (mainMenuChoice == 1)
{
Console.WriteLine("What is your name?");
username = Console.ReadLine();
}
else if (mainMenuChoice == 2)
{
Console.WriteLine("What was your username?");
username = Console.ReadLine();
saveGame = username + ".txt";
LoadGame(saveGame, ref Board);
}
else if (mainMenuChoice == 9)
{
Console.WriteLine("Closing in 3 seconds.");
Thread.Sleep(3000);
Environment.Exit(0);
}
Random randomOneX = new Random();
randomOneX = new Random(randomOneX.Next(0, 10));
int randomX = randomOneX.Next(0, BoardSize);
randomOneX = new Random(randomOneX.Next(0, 10));
int randomY = randomOneX.Next(0, BoardSize);
//Console.Write(randomX);
//Console.Write(randomY);
for (int i = 0; i < Board.GetUpperBound(0); i++)
{
for (int j = 0; j < Board.GetUpperBound(1); j++)
{
Board[i, j] = ' ';
}
}
Board[randomX, randomY] = 'x';
PrintBoard(Board);
int Row = 0;
int Column = 0;
bool wonGame = false;
Console.WriteLine();
Console.WriteLine("I've hidden a 't' in a map - you're job is to find the coordinates that have the 't' in.");
Console.WriteLine();
do
{
Console.Write("Please enter a Row: ");
bool validRow = false;
do
{
try
{
Row = int.Parse(Console.ReadLine());
validRow = true;
if (Row >= 10 || Row < 0)
{
Console.WriteLine("Please pick a number between 0-9: ");
validRow = false;
}
}
catch (Exception)
{
Console.WriteLine("Ooops, you've entered something that simply cannot be, please retry.");
}
} while (validRow == false);
Console.Write("Now enter a column: ");
bool validColumn = false;
do
{
try
{
Column = int.Parse(Console.ReadLine());
validColumn = true;
if (Column >= 10 || Column < 0)
{
Console.WriteLine("Please pick a number between 0-9: ");
validColumn = false;
}
}
catch (Exception)
{
Console.WriteLine("Ooops, you've entered something that simply cannot be, please retry.");
}
} while (validColumn == false);
if (Board[Row, Column] != 'x')
{
Board[Row, Column] = 'm';
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Clear();
Console.WriteLine("You've missed the target! Feel free to retry.");
Console.ForegroundColor = ConsoleColor.Gray;
wonGame = false;
PrintBoard(Board);
SaveGame(username, ref Board);
}
else
{
Board[Row, Column] = 't';
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You've won!");
Console.ForegroundColor = ConsoleColor.Gray;
wonGame = true;
}
} while (wonGame == false);
PrintBoard(Board);
Console.ReadLine();
}
private static void PrintBoard(char[,] Board)
{
Console.WriteLine();
Console.WriteLine("The map looks like this: ");
Console.WriteLine();
Console.Write(" ");
for (int Column = 0; Column < BoardSize; Column++)
{
Console.Write(" " + Column + " ");
}
Console.WriteLine();
for (int Row = 0; Row < BoardSize; Row++)
{
Console.Write(Row + " ");
for (int Column = 0; Column < BoardSize; Column++)
{
if (Board[Row, Column] == '-')
{
Console.Write(" ");
}
else if (Board[Row, Column] == 'x')
{
Console.Write(" ");
}
else
{
Console.Write(Board[Row, Column]);
}
if (Column != BoardSize)
{
Console.Write(" | ");
}
}
Console.WriteLine();
}
}
private static void SaveGame(string username, ref char [,] inBoard)
{
StreamWriter sGame = null;
string saveFilePath = username + ".txt";
try
{
sGame = new StreamWriter(saveFilePath);
}
catch (Exception)
{
Console.WriteLine("Ooops there seems to be an error with saving your game. Check the log for details.");
}
for (int i = 0; i < inBoard.GetUpperBound(0); i++)
{
for (int j = 0; j < inBoard.GetUpperBound(1); j++)
{
sGame.Write(inBoard[i, j]);
}
sGame.WriteLine("");
}
sGame.Close();
}
private static void LoadGame(string GameFile, ref char[,] Board)
{
StreamReader saveGameReader = null;
string Line = "";
try
{
saveGameReader = new StreamReader(GameFile);
}
catch (Exception e)
{
StreamWriter errorMessage = new StreamWriter("ErrorLog.txt", true);
errorMessage.WriteLine(DateTime.Now + "Error: " + e.ToString());
errorMessage.Close();
Debug.WriteLine(e.ToString());
Console.WriteLine("There was an error loading game, check log for info. (Press Enter to exit.)");
Console.ReadLine();
Environment.Exit(0);
}
char[,] loadedBoard = Board;
for (int Row = 0; Row < BoardSize; Row++)
{
Line = saveGameReader.ReadLine();
for (int Column = 0; Column < BoardSize; Column++)
{
loadedBoard[Row, Column] = Line[Column];
}
}
Board = loadedBoard;
saveGameReader.Close();
}
}
}
The link to a notepad screenshot is : https://imgur.com/a/hobuv
The GetUpperBound returns, as MSDN says
Gets the index of the last element of the specified dimension in the
array.
So you are getting 9 everywhere you use that method. To fix your code you need to change your loops in the saving and initialization of the Board array with <= as exit condition from the loops
for (int i = 0; i <= Board.GetUpperBound(0); i++)
{
for (int j = 0; j <= Board.GetUpperBound(1); j++)
{
Board[i, j] = ' ';
}
}
Your save has 9 rows but your board size was defined as 10
If your values in the file are like below
m m m m m m m m X m m m
m m m m m X m m X m m m
m m m X m m m m X m m m
Then you can try with this approach
int i = 0;
// Read the file and work it line by line.
string[] lines = File.ReadAllLines(gameFile);
foreach(string line in lines)
{
string[] columns = line.Split(' ');
for(int j = 0; j < columns.Length; j++)
{
loadedBoarder[i, j] = columns[j];
}
i++;
}
#captainjamie : Thanks for correcting my code.

my array of objects is only printing the last object entered C# [duplicate]

This question already has answers here:
C# dictionary value clearing out when I clear list previously assigned to it....why?
(6 answers)
What is the difference between a reference type and value type in c#?
(15 answers)
Closed 5 years ago.
My array of objects when printed only returns the value of the last group of objects entered. so if i enter a set of values in at the end it will only print out the last set of data.
namespace classschedule
{
class Program
{
static void Main(string[] args)
{
Course[] newarray = new Course[25];
Course[ , ] mycoursearray = new Course[6,5];
Course info = new Course();
int sections, classregistration, periods;
string names, classday;
for (int x1 = 0; x1 < 6; x1++)
{
for (int y1 = 0; y1 < 5; y1++)
{
mycoursearray[x1, y1] = new Course();
}
}
for (int x1 = 0; x1<5;x1++)
{
newarray[x1] = new Course();
}
int x = 0;
int y = 0;
for (int g = 0; g <= 4; g++)
{
for (int h = 0; h <= 5; h++)
{
info.busy = 0;
info.section = 0;
info.classize = 0;
info.classname = "";
mycoursearray[h, g] = info;
}
}
for (int j = 0; j < 24; j++)
{
Console.WriteLine("please enter class name: ");
names = Console.ReadLine();
char choice = 'y';
Console.WriteLine("please enter the section of your class: ");
sections = Convert.ToInt32(Console.ReadLine());
while (choice == 'y' || choice == 'Y')
{ if (sections <= 90)
{
choice = 'n';
}
else
{
Console.WriteLine("Section is to high must be below 90");
choice = 'n';
}
}
Console.WriteLine("Please enter the amount of students in the class: ");
classregistration = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the first letter of the day of the class **for thursday please type X");
classday = Console.ReadLine();
Console.WriteLine("Please enter your class period");
periods = Convert.ToInt32(Console.ReadLine());
x = periods - 1 ;
if (classday == "M")
y = 0;
else if (classday == "T")
y = 1;
else if (classday == "W")
y = 2;
else if (classday == "X")
y = 3;
else if (classday == "F")
y = 4;
info.classname = names;
info.section = sections;
info.classize = classregistration;
info.busy = 1;
mycoursearray[x, y] = info;
newarray[y+1] = info;
}
{
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 5 ; j++)
{
Console.Write(mycoursearray[i, j].classname +" " + mycoursearray[i, j].section+ " " + mycoursearray[i, j].classize);
//Console.Write(mycoursearray[i, j].section);
//Console.Write(mycoursearray[i, j].classize);
}
Console.WriteLine();
}
}
Console.ReadLine();
}
class Course
{
public int section;
public string classname;
public int classize;
public int busy;
}
}
}

Categories

Resources