goto function alternative and multiple printed lines in results - c#

Hoping someone can help. I'm still learning a lot each day as beginner. But have a few issues with the below.
The use of goto is a no-no from the research I have seen but I can't figure out an alternative loop to add while maybe? Or do?
When I enter text that I know will not return a result e.g. dsfgfhg and press enter I receive "Resource Not found " three times in the results. I assume this is because out of the list there are three entries and none match. How do I get one result instead of three when a resource is not found?
If I press enter twice in the console window without entering any text it returns everything in the list. Again I can't see a way to stop this. I guess I need to change the code to be explicit in some way?
Thanks again for your help.
using System;
using System.Collections.Generic;
class JunkList
{
public string Resource { get; set; }
public string Junk { get; set; }
public int Amount { get; set; }
public JunkList(string r, string j, int a)
{
this.Resource = r;
this.Junk = j;
this.Amount = a;
}
}
class Program
{
static void Main(string[] args) // this is a method called "Main" . It is called when the program starts.
{
start:
string searchName;
List<JunkList> infoList = new List<JunkList>();
infoList.Add(new JunkList("Screw", "Type Writer", 2));
infoList.Add(new JunkList("Screw", "Clip Board", 1));
infoList.Add(new JunkList("Screw", "Toy Car", 3));
Console.WriteLine("Which resource do you want to search for?? \n");
searchName = Console.ReadLine();
for (int i = 0; i < infoList.Count; i++)
{
if (infoList[i].Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
Console.WriteLine("Resource : " + infoList[i].Resource + "\n");
Console.WriteLine("Junk : " + infoList[i].Junk + "\n");
Console.WriteLine("Resource Amount : " + infoList[i].Amount + "\n");
}
else {
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
}
// wait for user to press a key. Then make an empty space and start over.
Console.ReadKey();
Console.WriteLine();
goto start; // go to start and run again
}
}

I recommend you to use 'single responsibility principle'. In your case that means that you should split your Main method into smaller methods. These methods do one simple action, i.e. responsibility.
Well, it will help:
You are right goto quite often is a bad practice (but not always). Put your code into while(true) and it would do the same but more clear. However, to close your application correctly receiving some char or key to exit would be better, e.g.
bool _runApplication = true;
while (_runApplication)
{
// code between "start:" and "goto start;"
if (Console.Read() == 'x')
{
_runApplication = false;
}
}
To solve this multiple Resource Not found output you can separate searching by name and printing searching results, e.g.
string searchName = Console.ReadLine();
List<JunkList> searchResult = GetJunkListsBySearchName(infoList, searchName);
if (searchResult.Count != 0)
{
foreach (var junkList in searchResult)
{
Console.WriteLine("Resource : " + junkList.Resource + "\n");
Console.WriteLine("Junk : " + junkList.Junk + "\n");
Console.WriteLine("Resource Amount : " + junkList.Amount + "\n");
}
}
else
{
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
where new method is:
private static List<JunkList> GetJunkListsBySearchName(List<JunkList> infoList, string searchName)
{
List<JunkList> output = new List<JunkList>();
foreach (var junkList in infoList)
{
if (junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
}
return output;
}
It is because of searchName is equal to en empty string. Add a simple if to solve it.
if (searchName.Length > 0 &&
junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
Applying all these points you will get code like this (only Program class modified):
class Program
{
static void Main(string[] args)
{
bool _runApplication = true;
while (_runApplication)
{
List<JunkList> infoList = CreateJunkList();
Console.WriteLine("Which resource do you want to search for?? \n");
string searchName = Console.ReadLine();
List<JunkList> searchResult = GetJunkListsBySearchName(infoList, searchName);
if (searchResult.Count != 0)
{
PrintJunkLists(searchResult);
}
else
{
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
Console.WriteLine();
if (Console.Read() == 'x')
{
_runApplication = false;
}
}
}
private static List<JunkList> CreateJunkList()
{
List<JunkList> infoList = new List<JunkList>();
infoList.Add(new JunkList("Screw", "Type Writer", 2));
infoList.Add(new JunkList("Screw", "Clip Board", 1));
infoList.Add(new JunkList("Screw", "Toy Car", 3));
return infoList;
}
private static void PrintJunkLists(List<JunkList> junkLists)
{
foreach (var junkList in junkLists)
{
PrintJunkList(junkList);
}
}
private static void PrintJunkList(JunkList junkList)
{
Console.WriteLine("Resource : " + junkList.Resource + "\n");
Console.WriteLine("Junk : " + junkList.Junk + "\n");
Console.WriteLine("Resource Amount : " + junkList.Amount + "\n");
}
private static List<JunkList> GetJunkListsBySearchName(List<JunkList> infoList, string searchName)
{
List<JunkList> output = new List<JunkList>();
foreach (var junkList in infoList)
{
if (searchName.Length > 0 &&
junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
}
return output;
}
}
I hope it helped)

Related

How can I add in code to make it impossible for a user to input an answer that is not listed? C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kenneth_ForquerENG_115
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Kenneth Forquer ENG 115");
This is where i store my questions and answers
List<Question> question = new List<Question>
{
new Question("What stage bleed air is used to start the engine?", new string[] { "8th", "9th", "1st", "13th" }, Question.multipleChoice, 2),
new Question("Igniters spark to combust the fuel.", new string[] { "true", "false" }, Question.trueAndFalse, 0),
new Question("What is the 1st stage in the cycle of the Gas turbine?", new string[] { "Intake", "Exhaust", "Power", "Combustion" }, Question.multipleChoice, 0),
new Question("What is the 3rd stage in the cycle of the Gas turbine?", new string[] { "Compression", "Combustion", "Intake", "Exhaust" }, Question.multipleChoice, 1),
new Question(" What is the last stage in the cycle of the Gas turbine?", new string[] { "Compression", "Power", "Intake", "Exhaust" }, Question.multipleChoice, 3),
new Question("Ngg refers to speed.", new string[] { "true", "false" }, Question.trueAndFalse, 0),
new Question("Npt refers to torque", new string[] { "true", "false" }, Question.trueAndFalse, 1),
new Question("What are the LM2500 metering points?", new string[] { "3", "2", "5.4", "All of the above" }, Question.multipleChoice, 3),
new Question("Which of these are a component of the compressor?", new string[] { "Inlet Plenum", "Gearbox", "Stator", "All of the above" }, Question.multipleChoice, 2),
new Question("What company manufactures the LM2500?", new string[] { "GM", "Ford", "Toyota", "Rolls Royce" }, Question.multipleChoice, 3)
};
for (int i = 0; i < question.Count; i++)
{
Console.WriteLine("--------------------------------");
Console.WriteLine("Question #" + (1 + i).ToString());
if (question[i].Ask())
{
Results.AddResult(question[i]);
Console.WriteLine("Press any key to continue to the next question.");
//Console.WriteLine("--------------------------------");
}
else
{
Results.AddResult(question[i]);
}
Console.Clear();
}
Console.WriteLine("--------------------------------");
Console.WriteLine("End of the first attempt.");
int tempScore = 0;
for (int i = 0; i < Results.firstResults.Count; i++)
{
if (Results.firstResults[i].isCorrect)
{
tempScore++;
}
}
Console.WriteLine("Your current mark is: " + tempScore + "/" + Results.firstResults.Count.ToString());
Console.WriteLine("--------------------------------");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
Results.RunSecondAttemp();
Console.WriteLine("--------------------------------");
Console.WriteLine("End of the Quiz!");
int tempFinalScore = 0;
for (int i = 0; i < Results.finalResults.Count; i++)
{
if (Results.finalResults[i].isCorrect)
{
tempFinalScore++;
}
}
Console.WriteLine("Your final mark is: ");
Console.WriteLine(tempFinalScore + "/" + Results.finalResults.Count.ToString());
if (tempFinalScore > 5)
{
Console.WriteLine("Good Job!");
}
else
{
Console.WriteLine("Better luck next time...");
}
Console.WriteLine("--------------------------------");
Console.WriteLine("Press any key to exit the console...");
Console.ReadKey();
}
}
}
namespace Kenneth_ForquerENG_115
{
class Question
{
public string question;
public string[] answers;
public bool isCorrect;
public string inputAnswer;
private int correctIndex;
private string questionType;
public static string trueAndFalse = "TF";
public static string multipleChoice = "MC";
Here is where the input for the questions are.
public Question(string q, string[] answersList, string typeOfQuestion, int correctAnswer)
{
question = q;
questionType = typeOfQuestion;
if (questionType == multipleChoice)
answers = new string[4];
else if (questionType == trueAndFalse)
answers = new string[2];
for (int i = 0; i < answersList.Length; i++)
{
this.answers[i] = answersList[i];
}
correctIndex = correctAnswer;
}
public bool Ask()
{
Console.WriteLine(question);
if (questionType == multipleChoice)
{
Console.WriteLine("Input an answer from the following possibilities...");
}
else
{
Console.WriteLine("Please input 'true' or 'false'... ");
}
for (int i = 0; i < answers.Length; i++)
{
Console.WriteLine(answers[i]);
}
Console.WriteLine("--------------------------------");
inputAnswer = Console.ReadLine();
if (inputAnswer == answers[correctIndex])
{
Console.Clear();
Console.WriteLine("Correct!");
isCorrect = true;
Console.WriteLine("Press any key to continue to the next question.");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Incorrect.");
isCorrect = false;
Console.WriteLine("Press any key to continue to the next question.");
Console.ReadKey();
}
return isCorrect;
}
public void PrintQuestion()
{
Console.WriteLine(question);
if (questionType == multipleChoice)
{
Console.WriteLine("Input an answer from the following possibilities...");
}
else
{
Console.WriteLine("Please input 'true' or 'false'... ");
}
for (int i = 0; i < answers.Length; i++)
{
Console.WriteLine(answers[i]);
}
}
}
}
namespace Kenneth_ForquerENG_115
{
static class Results
{
public static List<Question> firstResults = new List<Question>();
public static List<Question> finalResults = new List<Question>();
public static void AddResult(Question questionResult)
{
firstResults.Add(questionResult);
}
public static void AddFinalResult(Question question)
{
finalResults.Add(question);
}
public static void RunSecondAttemp()
{
Console.Clear();
Console.WriteLine("Attempt #2:");
for (int i = 0; i < firstResults.Count; i++)
{
Console.WriteLine("\n--------------------------------");
Console.WriteLine("\nQuestion " + (1 + i).ToString());
if (firstResults[i].isCorrect)
{
Console.WriteLine("\nThis one was correct!");
firstResults[i].PrintQuestion();
Console.WriteLine("Your answer: " + firstResults[i].inputAnswer);
AddFinalResult(firstResults[i]);
Console.WriteLine("Press any key to continue to the next question.");
Console.ReadKey();
}
else
{
Console.WriteLine("This one was wrong on the first attempt! Please try again.");
if (firstResults[i].Ask())
{
AddFinalResult(firstResults[i]);
Console.WriteLine("Press any key to continue to the next question.");
}
else
{
AddFinalResult(firstResults[i]);
}
Console.WriteLine("\n--------------------------------");
}
Console.Clear();
}
}
}
}
Basically what I am trying to do is make it where the user can only input the answers to the questions. If they type in something not listed it will display an error message, something like "incorrect input, please choose from given answers." So if they type something not listed that message would appear and then go back to the question until they type on of the choices.
One option would be to check if their answer is among the answer choices before checking if the answer is correct. You could do it like this:
while (Array.IndexOf(answers, inputAnswer) < 0)
{
Console.WriteLine("incorrect input, please choose from given answers.");
inputAnswer = Console.ReadLine();
}
Array.IndexOf will return -1 if inputAnswer is not in the answers array. The while loop will not break until the user inputs an answer that is in the answers array, and inputAnswer will contain an answer that is in answers when the loop breaks.
This would go in the Ask method before the line containing
if (inputAnswer == answers[correctIndex])

Unity3d error CS0103: The name `PeerState' does not exist in the current context

I got this error i cant really fix it i dont know what does it want me to do .
here is the code if you need more of the codes tell me if they will help you solve it .
using System;
using UnityEngine;
using Random = UnityEngine.Random;
public class LobbyMenu : MonoBehaviour
{
//private string[]FirstName = new string[7]{"Clever", "Cunning", "Wise", "Awesome", "Amazing", "Dark", "Heroic"};
//private string[]LastName = new string[7]{"Rogue", "Wizard", "Mage", "Summoner", "Warrior", "Assassin", "Ranger"};
private string roomName = "myRoom";
private bool MessageRoomNameTaken = false;
private float MessageRoomTakenTimeToDisplay = 0;
private Vector2 scrollPos = Vector2.zero;
private bool connectFailed = false;
public static readonly string SceneNameMenu = "LobbyScene";
public static readonly string SceneNameGame = "GameScene";
public void Awake()
{
// this makes sure we can use PhotonNetwork.LoadLevel() on the master client and all clients in the same room sync their level automatically
PhotonNetwork.automaticallySyncScene = true;
// the following line checks if this client was just created (and not yet online). if so, we connect
if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated)
{
// Connect to the photon master-server. We use the settings saved in PhotonServerSettings (a .asset file in this project)
PhotonNetwork.ConnectUsingSettings("1.0");
}
// generate a name for this player, if none is assigned yet
if (String.IsNullOrEmpty(PhotonNetwork.playerName))
{
//PhotonNetwork.playerName = "Guest" + Random.Range(1, 9999);
//PhotonNetwork.playerName = FirstName[Random.Range(0, 6)] + " " + LastName[Random.Range(0, 6)];
PhotonNetwork.playerName = MainMenu.username;
}
// if you wanted more debug out, turn this on:
// PhotonNetwork.logLevel = NetworkLogLevel.Full;
}
public void OnGUI()
{
if (!PhotonNetwork.connected)
{
if (PhotonNetwork.connecting)
{
GUILayout.Label("Connecting to: " + PhotonNetwork.ServerAddress);
}
else
{
GUILayout.Label("Not connected. Check console output. Detailed connection state: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.ServerAddress);
}
if (this.connectFailed)
{
GUILayout.Label("Connection failed. Check setup and use Setup Wizard to fix configuration.");
GUILayout.Label(String.Format("Server: {0}", new object[] {PhotonNetwork.ServerAddress}));
GUILayout.Label("AppId: " + PhotonNetwork.PhotonServerSettings.AppID);
if (GUILayout.Button("Try Again", GUILayout.Width(100)))
{
this.connectFailed = false;
PhotonNetwork.ConnectUsingSettings("1.0");
}
}
return;
}
GUI.skin.box.fontStyle = FontStyle.Bold;
GUI.Box(new Rect((Screen.width - 400) / 2, (Screen.height - 350) / 2, 400, 300), "Join or Create a Room");
GUILayout.BeginArea(new Rect((Screen.width - 400) / 2, (Screen.height - 350) / 2, 400, 300));
GUILayout.Space(25);
// Player name
GUILayout.BeginHorizontal();
GUILayout.Label("Player name:", GUILayout.Width(100));
GUILayout.Label(PhotonNetwork.playerName);
//PhotonNetwork.playerName = GUILayout.TextField(PhotonNetwork.playerName);
GUILayout.Space(105);
if (GUI.changed)
{
// Save name
PlayerPrefs.SetString("playerName", PhotonNetwork.playerName);
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
// Join room by title
GUILayout.BeginHorizontal();
GUILayout.Label("Roomname:", GUILayout.Width(100));
this.roomName = GUILayout.TextField(this.roomName);
if (GUILayout.Button("Create Room", GUILayout.Width(100)))
{
foreach (RoomInfo roomInfo in PhotonNetwork.GetRoomList())
{
if (roomInfo.name == this.roomName) {MessageRoomNameTaken = true; break;}
}
if (MessageRoomNameTaken==false) PhotonNetwork.CreateRoom(this.roomName, new RoomOptions() { maxPlayers = 2 }, null);
Debug.Log("OnJoinedRoom");
}
GUILayout.EndHorizontal();
// Create a room (fails if exist!)
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
//this.roomName = GUILayout.TextField(this.roomName);
if (GUILayout.Button("Join Room", GUILayout.Width(100)))
{
PhotonNetwork.JoinRoom(this.roomName);
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
// Join random room
GUILayout.BeginHorizontal();
GUILayout.Label(PhotonNetwork.countOfPlayers + " users are online in " + PhotonNetwork.countOfRooms + " rooms.");
GUILayout.FlexibleSpace();
if (GUILayout.Button("Join Random", GUILayout.Width(100)))
{
PhotonNetwork.JoinRandomRoom();
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
if (PhotonNetwork.GetRoomList().Length == 0)
{
GUILayout.Label("Currently no games are available.");
GUILayout.Label("Rooms will be listed here, when they become available.");
}
else
{
int roomcount = PhotonNetwork.GetRoomList().Length;
if (roomcount==1 )GUILayout.Label("1 room is currently available:");
else GUILayout.Label(PhotonNetwork.GetRoomList().Length + " rooms are currently available:");
// Room listing: simply call GetRoomList: no need to fetch/poll whatever!
this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
foreach (RoomInfo roomInfo in PhotonNetwork.GetRoomList())
{
GUILayout.BeginHorizontal();
GUILayout.Label(roomInfo.name + " " + roomInfo.playerCount + "/" + roomInfo.maxPlayers);
if (GUILayout.Button("Join"))
{
PhotonNetwork.JoinRoom(roomInfo.name);
}
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
GUILayout.EndArea();
if (MessageRoomNameTaken == true) {
MessageRoomTakenTimeToDisplay = 5; // we will display the warning for this number of seconds
MessageRoomNameTaken = false;
}
if (MessageRoomTakenTimeToDisplay >0 ) { GUI.contentColor = Color.red;
GUI.Label(new Rect(400,50,300,60), "The room with this name already exists");
MessageRoomTakenTimeToDisplay = MessageRoomTakenTimeToDisplay - Time.deltaTime;
}
}
// We have two options here: we either joined(by title, list or random) or created a room.
public void OnJoinedRoom()
{
Debug.Log("OnJoinedRoom");
}
public void OnCreatedRoom()
{
Debug.Log("OnCreatedRoom");
PhotonNetwork.LoadLevel(SceneNameGame);
}
public void OnDisconnectedFromPhoton()
{
Debug.Log("Disconnected from Photon.");
}
public void OnFailedToConnectToPhoton(object parameters)
{
this.connectFailed = true;
Debug.Log("OnFailedToConnectToPhoton. StatusCode: " + parameters + " ServerAddress: " + PhotonNetwork.networkingPeer.ServerAddress);
}
}
i used photon network so yea . so please just rewrite or fix it or atleast tell me what to do i have no clue .
// the following line checks if this client was just created (and not yet online). if so, we connect
if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated)
{
// Connect to the photon master-server. We use the settings saved in PhotonServerSettings (a .asset file in this project)
PhotonNetwork.ConnectUsingSettings("1.0");
}
If you check the docs for PhotonNetwork you'll see that the PhotonNetwork.connectionStateDetailed static property returns a ClientState enum value (so not a PeerState).
Source: https://doc-api.photonengine.com/en/pun/current/class_photon_network.html
And here is the enum documentation: Enum Documentation
So, change:
if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated)
to
if (PhotonNetwork.connectionStateDetailed == ClientState.PeerCreated)

Using array in different methods [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
well i'm doing a code in C#,
this code allows you to add items to your code, price, unit, etc. save them in an array, and a menu will display the aggregated items.
I have a problem because I do it this way and apparently my code don't work, could someone help me?.
King Regards.
I'm newest in this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Market
{
public class Menu
{
public static int item { get; set; }
public static string[] product = new string[item];
public static string[] code = new string[item];
public static string[] price = new string[item];
public static string[] unit = new string[item];
public void showMenu()
{
Console.WriteLine("1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit");
//Menu
while (true)
{
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product[i] = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
code[i] = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
price[i] = Console.ReadLine();
Console.Write("Unit[" + i + "]: ");
unit[i] = Console.ReadLine();
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
for (int i = 0; i < item; i++)
{
Console.WriteLine(product[i] + " " + code[i] + " " + price[i] + " " + unit[i]);
}
}
}
}
There are few problems with the code.
Arrays that you created for product, code, etc are of zero size as item value is by default. Inserting any value to 0 sized array throws an exception.
Also you should be cautious on accessing the static fields in not static context.
.
I would suggest define a class with these properties and use the List to keep collection.
public class Product
{
public string Name {get;set;}
public string Code {get;set;}
public double Price {get;set;}
public int Unit {get;set;}
}
Now modify your additem to create products.
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
var product = new Product();
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product.Name = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
product.Code = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
product.Price = double.Parse(Console.ReadLine()); //read as double value.
Console.Write("Unit[" + i + "]: ");
product.Unit = int.Parse(Console.ReadLine()); // Read as int value
products.Add(product); // products is global/class variable.
}
}
Check this Demo, it gives you an idea to proceed.
You are initializing yours arrays with a zero length. You arrays and item property are static that are initializing at application start. So when you change item field your arrays have already been initialized with default value of int, that is zero. You should initialize your arrays after setting the item property. And even after this you will not be able to add items to your arrays. Try to use List<> instead.
The issue is the static variable item is initialized to 0 when the class loads. Once you change it by reading in the user inputted value, you don't allocate properly sized arrays for your static variables. You can fix this by doing so after reading in the value:
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
// initialize static vars to correct size, now that we have #items
product = new string[item];
code = new string[item];
price = new string[item];
unit = new string[item];
Console.WriteLine("Insert the items.");
for (int i = 0; i < item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product[i] = Console.ReadLine();
Console.Write("Code[" + i + "]: ");
code[i] = Console.ReadLine();
Console.Write("Price[" + i + "]: ");
price[i] = Console.ReadLine();
Console.Write("Unit[" + i + "]: ");
unit[i] = Console.ReadLine();
}
}
You can see the fixed code in action at https://dotnetfiddle.net/n5lWTQ !
Just to get you started... you instantiated your arrays in the field declaration with a size of item
public static int item { get; set; }
public static string[] product = new string[item];
public static string[] code = new string[item];
public static string[] price = new string[item];
public static string[] unit = new string[item];
The problem with this is that the moment you access the Menu class, these lines of code immediately gets executed. And since the default value of an int is 0, you will have your array sizes to be 0. Try applying breakpoints into those line and you'll see.
Now what you can do here is instantiate them once you have set the value of item. So you will have your code to be something like this...
public static int item { get; set; }
//just declare your arrays here
public string[] product;
public string[] code;
public string[] price;
public string[] unit;
public void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
//instantiate your arrays here since item will have a value you have set it into.
product = new string[item];
code = new string[item];
price = new string[item];
unit = new string[item];
Console.WriteLine("Insert the items.");
You could try using a list of objects containing the required fields of your item. A generic list will allow you to dynamically add items to the list without having to set the size during initialization. This means you can add items (using option 1) as many times as you like without changing the arrays.
In addition to setting the arrays to zero size when you initialized your class (as other answers have suggested), it looked as if you were re-using your int item property each time you wanted to add new items to your lists. This means that the variable was changing so your ShowItems() method did not function correctly.
Here is a working example:
using System;
using System.Collections.Generic;
namespace Market
{
public class Menu
{
public struct Item
{
public string product;
public string code;
public string price;
public string unit;
}
public static List<Item> items = new List<Item>();
public static void showMenu()
{
//Menu
while (true)
{
Console.WriteLine("\n1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit");
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
int numbItemsToAdd = Convert.ToInt32(Console.ReadLine()); // needs validation
Console.WriteLine("Insert the items.");
for (int i = 0; i < numbItemsToAdd; i++)
{
Item item = new Item();
Console.WriteLine("\nItem[" + (i + 1) +"]: ");
Console.Write("Product[" + (i + 1) +"]: ");
item.product = Console.ReadLine();
Console.Write("Code[" + (i + 1) + "]: ");
item.code = Console.ReadLine();
Console.Write("Price[" + (i + 1) + "]: ");
item.price = Console.ReadLine();
Console.Write("Unit[" + (i + 1) + "]: ");
item.unit = Console.ReadLine();
items.Add(item);
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
foreach(Item i in items)
{
Console.WriteLine(i.product + " " + i.code + " " + i.price + " " + i.unit);
}
}
public static void Main()
{
showMenu();
}
}
}
public class Menu
{
public static int item { get; set; }
public static List<string> product = new List<string>();
public static List<string> code = new List<string>();
public static List<string> price = new List<string>();
public static List<string> unit = new List<string>();
public void showMenu()
{
//Menu
while (true)
{
Console.WriteLine("\n1.- Add new item");
Console.WriteLine("2.- Show items");
Console.WriteLine("3.- Exit \n");
string option = Console.ReadLine();
switch (option)
{
case "1":
addItem();
break;
case "2":
showItems();
break;
case "3":
System.Environment.Exit(-1);
Console.ReadKey();
break;
default:
Console.WriteLine("Select one valid option..");
break;
}
}
}
public static void addItem()
{
Console.WriteLine("\nAmount of items to add");
item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert the items.");
for (int i = 1; i <= item; i++)
{
Console.WriteLine("\nItem[" + i + "]: ");
Console.Write("Product[" + i + "]: ");
product.Add(Console.ReadLine());
Console.Write("Code[" + i + "]: ");
code.Add(Console.ReadLine());
Console.Write("Price[" + i + "]: ");
price.Add(Console.ReadLine());
Console.Write("Unit[" + i + "]: ");
unit.Add(Console.ReadLine());
}
}
public static void showItems()
{
Console.WriteLine("******* SHOW ITEMS *******");
Console.WriteLine("Product ------------- Code ------------- Price ------------- Unit");
for (int i = 0; i < item; i++)
{
Console.WriteLine(product[i] + " " + code[i] + " " + price[i] + " " + unit[i]);
}
}
}

TaskFactory changing parameters

So i have the following code:
public void tViewers(int? start, int? stop)
{
for (int? i0 = start; i0 <= stop; i0++)
{
StartLabel:
Viewer v = new Viewer(channelNameTextBox.Text, this);
if (urlWithTokens.Contains(v.getViewerLink()))
{
goto StartLabel;
}
else
{
if (v.getViewerLink() != "")
{
Console.WriteLine("[V #" + i0 + "] SUCCESS");
urlWithTokens.Add(v.getViewerLink());
}
else
{
Console.WriteLine("Channel not found.");
showError("The channel name is not valid.", true);
this.Invoke(new Action(() => this.botControlls.Enabled = true));
urlWithTokens.Clear();
}
}
v = null; // clear
}
Console.WriteLine("[V] " + start + " to " + stop + " COMPLETED");
start = null;
stop = null;
GC.SuppressFinalize(this);
}
Which is executed by:
for (int i = 0; i < maxThreads; i++)
{
taskFactory.StartNew(() => tViewers(someValue, someHigherValue));
}
The problem here is the local parameters "start" and "stop" in tViwers and it returst some stange values.
fx if i print "start" it should return the "someValue" and "someHigherValue" depending on what "thread" it is running in, however it returns strange values 40, 50 or something (even if it should return 1, 2, 3...
I have tried using the GC.SuppressFinalize(this); and setting the int's to null my allowing them to be null (int?). However the problem is still there...
Can someone help me?

Pick random word from list?

I´m having trouble picking a random word from a list in another file.
Actually I can´t even get it to choose any word. I´m not sure how to connect the 2 files so to say.
Hoping someone can help out, I´m a beginner so please explain as easy as possible:)
I have 2 files, one is called program.cs and the other is called WordList.cs
I´m gonna paste all my code but first the little snip that I´m having problem with. I just can´t figure out how to write the code correct.
Here is the little part which is called Pick word:
//PICK WORD
static string pickWord()
{
string returnword = "";
TextReader file = new StreamReader(words);
string fileLine = file.ReadLine();
Random randomGen = new Random();
returnword = words[randomGen.Next(0, words.Count - 1)];
return returnword;
}
And here is all the code in Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Hangman
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Title = "C# Hangman";
Console.WriteLine("Welcome To C# Hangman!");
//MENU
int MenuChoice = 0;
while (MenuChoice != 4)
{
Console.Write("\n\t1) Add words");
Console.Write("\n\t2) Show list of words");
Console.Write("\n\t3) Play");
Console.Write("\n\t4) Quit\n\n");
Console.Write("\n\tChoose 1-4: "); //Choose meny item
MenuChoice = Convert.ToInt32(Console.ReadLine());
WordList showing = new WordList();
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
showing.AddWord(insert);
Console.Write("\n\tList of words\n\n");
showing.ListOfWords();
break;
case 2:
Console.Write("\n\tList of words\n\n");
showing.ListOfWords();
break;
case 3: //Running game
int numGuessesInt = -1;
while (numGuessesInt == -1)
{
/* Sets the number of guesses the user has to guess the word*/
pickNumGuesses(ref numGuessesInt);
}
/* Randomly picks a word*/
string word = pickWord();
/* Creates a list of characters that will show */
List<char> guessedLetters = new List<char>();
bool solved = false;
while (solved == false)
{
/* Displaying a string to the user based on the user's correct guesses.
* If nothing is correct string will return "_ _ _ " */
string wordToDisplay = displayWord(guessedLetters, word);
/* If the string returned contains the "_" character, all the
* correct letters have not been guessed, so checking if user
* has lost, by checking if numGuessesLeft is less than 1.*/
if (!wordToDisplay.Contains("_"))
{
solved = true;
Console.WriteLine("You Win! The word was " + word);
/* Check if the user wants to play again. If they do,
* then solved is set to true, will end the loop,
* otherwise, checkIfPlayAgain will close the program.*/
checkIfPlayAgain();
}
else if (numGuessesInt <= 0)
{
solved = true;
Console.WriteLine("You Lose! The word was " + word);
checkIfPlayAgain();
}
else
{
/* If the user has not won or lost, call guessLetter,
* display the word, minus guesses by 1*/
guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
}
}
break;
case 4:
Console.WriteLine("\n\tEnd game?\n\n");
break;
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
}
}
// ****** PICK NUMBER OF GUESSES ******
static void pickNumGuesses(ref int numGuessesInt)
{
string numGuessesString = "";
Console.WriteLine("Pick a number of guesses");
numGuessesString = Console.ReadLine();
try
{
numGuessesInt = Convert.ToInt32(numGuessesString);
if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
{
throw new Exception();
}
}
catch (Exception)
{
numGuessesInt = -1;
Console.WriteLine("Error: Invalid Number of Guesses");
}
}
//PICK WORD
static string pickWord()
{
string returnword = "";
TextReader file = new StreamReader(words);
string fileLine = file.ReadLine();
Random randomGen = new Random();
returnword = words[randomGen.Next(0, words.Count - 1)];
return returnword;
}
// ****** Display word ******
static string displayWord(List<char> guessedCharacters, string word)
{
string returnedWord = "";
if (guessedCharacters.Count == 0)
{
foreach (char letter in word)
{
returnedWord += "_ ";
}
return returnedWord;
}
foreach (char letter in word)
{
bool letterMatch = false;
foreach (char character in guessedCharacters)
{
if (character == letter)
{
returnedWord += character + " ";
letterMatch = true;
break;
}
else
{
letterMatch = false;
}
}
if (letterMatch == false)
{
returnedWord += "_ ";
}
}
return returnedWord;
}
// ****** Guess letter ******
static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
{
string letters = "";
foreach (char letter in guessedCharacters)
{
letters += " " + letter;
}
Console.WriteLine("Guess a letter");
Console.WriteLine("Guessed Letters: " + letters);
Console.WriteLine("Guesses Left: " + numGuessesLeft);
Console.WriteLine(wordToDisplay);
string guess = Console.ReadLine();
char guessedLetter = 'a';
try
{
guessedLetter = Convert.ToChar(guess);
if (!Char.IsLetter(guessedLetter))
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("Error: Invalid Letter Choice");
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
bool repeat = false;
for (int i = 0; i < guessedCharacters.Count; i++)
{
if (guessedCharacters[i] == guessedLetter)
{
Console.WriteLine("Error: Invalid Letter Choice");
repeat = true;
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
}
if (repeat == false)
{
guessedCharacters.Add(guessedLetter);
numGuessesLeft -= 1;
}
}
// ****** Check to see if player wants to play again. ******
static void checkIfPlayAgain()
{
Console.WriteLine("Would you like to play again? (y/n)");
string playAgain = Console.ReadLine();
if (playAgain == "n")
{
Environment.Exit(1);
}
}
}
And here is the code for WordList.cs
using System;
using System.Collections.Generic;
class WordList
{
List <string> words = new List<string>();
public void ListOfWords()
{
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public void AddWord(string value){
words.Add(value);
}
}
I have made some changes to your code. The code works now but is far from perfect.
Your solution has two files Program.cs and Wordlist.cs, which looks like this
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
public class Hangman
{
/*
* Some notes on your code:
* use naming convention for methods and fields, i.e. methods names start with a capital letter
* use modifiers for methods, i.e private, public, protected in your method declarations
* make variables private if you use them on several methods
* and finally: read a book on c#
*
*/
private static WordList words;
private static Random randomGen = new Random();
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Title = "C# Hangman";
Console.WriteLine("Welcome To C# Hangman!");
initializeWordList();
//MENU
int MenuChoice = 0;
while (MenuChoice != 4)
{
Console.Write("\n\t1) Add words");
Console.Write("\n\t2) Show list of words");
Console.Write("\n\t3) Play");
Console.Write("\n\t4) Quit\n\n");
Console.Write("\n\tChoose 1-4: "); //Choose meny item
MenuChoice = Convert.ToInt32(Console.ReadLine());
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
words.Add(insert);
Console.Write("\n\tList of words\n\n");
foreach (string w in words) // Display for verification
Console.WriteLine(w);
break;
case 2:
Console.Write("\n\tList of words\n\n");
foreach (string w in words) // Display for verification
Console.WriteLine(w);
break;
case 3: //Running game
int numGuessesInt = -1;
while (numGuessesInt == -1)
{
/* Sets the number of guesses the user has to guess the word*/
pickNumGuesses(ref numGuessesInt);
}
/* Randomly picks a word*/
string word = PickWord();
/* Creates a list of characters that will show */
List<char> guessedLetters = new List<char>();
bool solved = false;
while (solved == false)
{
/* Displaying a string to the user based on the user's correct guesses.
* If nothing is correct string will return "_ _ _ " */
string wordToDisplay = displayWord(guessedLetters, word);
/* If the string returned contains the "_" character, all the
* correct letters have not been guessed, so checking if user
* has lost, by checking if numGuessesLeft is less than 1.*/
if (!wordToDisplay.Contains("_"))
{
solved = true;
Console.WriteLine("You Win! The word was " + word);
/* Check if the user wants to play again. If they do,
* then solved is set to true, will end the loop,
* otherwise, checkIfPlayAgain will close the program.*/
checkIfPlayAgain();
}
else if (numGuessesInt <= 0)
{
solved = true;
Console.WriteLine("You Lose! The word was " + word);
checkIfPlayAgain();
}
else
{
/* If the user has not won or lost, call guessLetter,
* display the word, minus guesses by 1*/
guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
}
}
break;
case 4:
Console.WriteLine("\n\tEnd game?\n\n");
break;
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
}
}
private static void initializeWordList()
{
words = new WordList();
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
}
// ****** PICK NUMBER OF GUESSES ******
private static void pickNumGuesses(ref int numGuessesInt)
{
string numGuessesString = "";
Console.WriteLine("Pick a number of guesses");
numGuessesString = Console.ReadLine();
try
{
numGuessesInt = Convert.ToInt32(numGuessesString);
if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
{
throw new Exception();
}
}
catch (Exception)
{
numGuessesInt = -1;
Console.WriteLine("Error: Invalid Number of Guesses");
}
}
//PICK WORD
private static string PickWord()
{
return words[randomGen.Next(0, words.Count() - 1)];
}
// ****** Display word ******
private static string displayWord(List<char> guessedCharacters, string word)
{
string returnedWord = "";
if (guessedCharacters.Count == 0)
{
foreach (char letter in word)
{
returnedWord += "_ ";
}
return returnedWord;
}
foreach (char letter in word)
{
bool letterMatch = false;
foreach (char character in guessedCharacters)
{
if (character == letter)
{
returnedWord += character + " ";
letterMatch = true;
break;
}
else
{
letterMatch = false;
}
}
if (letterMatch == false)
{
returnedWord += "_ ";
}
}
return returnedWord;
}
// ****** Guess letter ******
static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
{
string letters = "";
foreach (char letter in guessedCharacters)
{
letters += " " + letter;
}
Console.WriteLine("Guess a letter");
Console.WriteLine("Guessed Letters: " + letters);
Console.WriteLine("Guesses Left: " + numGuessesLeft);
Console.WriteLine(wordToDisplay);
string guess = Console.ReadLine();
char guessedLetter = 'a';
try
{
guessedLetter = Convert.ToChar(guess);
if (!Char.IsLetter(guessedLetter))
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("Error: Invalid Letter Choice");
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
bool repeat = false;
for (int i = 0; i < guessedCharacters.Count; i++)
{
if (guessedCharacters[i] == guessedLetter)
{
Console.WriteLine("Error: Invalid Letter Choice");
repeat = true;
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
}
if (repeat == false)
{
guessedCharacters.Add(guessedLetter);
numGuessesLeft -= 1;
}
}
// ****** Check to see if player wants to play again. ******
static void checkIfPlayAgain()
{
Console.WriteLine("Would you like to play again? (y/n)");
string playAgain = Console.ReadLine();
if (playAgain == "n")
{
Environment.Exit(1);
}
}
}
Wordlist.cs
using System;
using System.Collections.Generic;
public class WordList : List<string>
{
}
Here is the very simple solution:
Populate your list just one time, or when ever you add any word, call this method. Code:
private void PopulateTheWordList()
{
Console.Write("\n\tAdd a word\n\n");
WordList.Add(Console.ReadLine());
}
Now just call this method to get random words:
private string PickWord()
{
Random ran = new Random();
return WordList[ran.Next(0, WordList.Count)];
}
If you need to create List of words in another class, then use keyword static:
static List<string> WordList = new List<string>();
Now you can call it by just writing the class name, like YourClassName.WordList
Try creating a Static Class and add a method for returning your List, you will then be able to access your wordlist.
example:
static class WordList
{
static List<string> words = new List<string>();
public static void ListOfWords()
{
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
words.Add(value);
}
}
You would then change your switch statement to look something like this.
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
WordList.AddWord(insert);
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
case 2:
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
....
and your pickWord Method would look like this:
static string pickWord()
{
string returnword = "";
Random randomGen = new Random();
returnword = WordList.GetWords()[randomGen.Next(0, WordList.GetWords().Count() - 1)];
return returnword;
}
I modified your Wordlist class so that it can use a file to maintain your Words between uses of your program, just incase that is what was being asked of you.
static class WordList
{
static string filePath = #"C:\temp\Word.txt";
static List<string> words = new List<string>();
private static void CheckFile()
{
//Makes sure our base words are saved to the file
if (!File.Exists(#"C:\temp\Word.txt"))
{
using (TextWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("test");
writer.WriteLine("dog");
writer.WriteLine("shit");
}
}
}
public static void ListOfWords()
{
CheckFile();
words.Clear();
using (TextReader file = new StreamReader(filePath))
{
char[] delineators = new char[] { '\r', '\n' };
string[] tempWords = file.ReadToEnd().Split(delineators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in tempWords)
{
words.Add(line);
}
}
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
CheckFile();
using (TextWriter writer = new StreamWriter(filePath,true ))
{
writer.WriteLine(value);
}
}
}

Categories

Resources