C# storing user input in string array - c#

I am trying to make a potential two player program where one user is prompted to enter a question and then prompted to enter the answer to that question both of which will be stored in a two dimensional array. The first player will be able to enter up to 10 questions. After both the question and answer to that question are stored, I would like to then be able to have the second player prompted to answer the questions the first player asked.
Right now I'm stuck at a pretty basic part which is storing the questions and answers in the array.
Here is the code I have so far my first class:
class MakeOwnQuestion
{
string question;
string answer;
string[,] makequestion = new string[10, 2];
public void MakeQuestion(string question, string answer, int index)
{
if (index < makequestion.Length)
{
makequestion[index, 0] = question;
makequestion[index, 1] = answer;
}
}
My second class:
class MakeOwnQuestionUI
{
MakeOwnQuestion newquestion;
public void MainMethod()
{
PopulateArray();
}
void PopulateArray()
{
string question;
string answer;
Console.WriteLine("Enter Your Question: ");
question = Console.ReadLine();
Console.WriteLine("Enter Your Answer: ");
answer = Console.ReadLine();
newquestion.MakeQuestion(question, answer, 0);
Console.WriteLine("Enter Your Question: ");
question = Console.ReadLine();
Console.WriteLine("Enter Your Answer: ");
answer = Console.ReadLine();
newquestion.MakeQuestion(question, answer, 1);
}
}
I keep getting the same error message after the user enters their first answer
"Object reference not set to an instance of an object"

You need to initialize your newquestion instance:
MakeOwnQuestion newquestion = new MakeOwnQuestion();
I'd also recommend you use GetLength rather than Length for a multidimensional array:
if (index < makequestion.GetLength(0))
{
...
}
Or better yet, just a List<T> of some type, e.g. Tuple<string, string>:
class MakeOwnQuestion
{
List<Tuple<string, string>> makequestion = new List<Tuple<string, string>>();
public void MakeQuestion(string question, string answer, int index)
{
makequestion.Add(Tuple.Create(question, answer));
}
}

Related

C# Confused on passing parameters with a string involved

Really confused on this homework assignment we have , I am not looking for the answer but some guidance. I am confused on how i would accept the user input and pass it through to pull one of these response from the array depending on their input being 1 through 5. Here is the problem below.
Create a program called Magic8Ball (console or GUI, your choice). The program should contain a method (written by you) that declares an array of at least five strings with Magic 8-Ball type phrases such as "The answer seems certain" (you can make up the phrases or use traditional ones--google magic 8ball phrases to see them. Your method should accept one parameter, an index into the array of phrase strings. Your method will display the phrase associated with the index that's passed into the method. For example, if the string at phrases[4] was "The future seems cloudy" and the calling program passed the value 4 into your method then the method would display "The future seems cloudy." Include error-handling in your method so that only valid indexes will produce output.
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
int response;
string[] quotes;
quotes = new string[5];
{
quotes[1] = ("Today is going to be a good day");
quotes[2] = ("Tomorrow is going to rain");
quotes[3] = ("Next month will be blissful");
quotes[4] = ("You are very lucky to be here");
quotes[5] = ("The love of your life notices you");
};
WriteLine("Please enter a number between one and five");
response = Convert.ToInt32(ReadLine());
if (response = quotes[1])
{
}
}
}
}
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
int response;
string[] quotes = new string [5];
{
quotes[0] = ("Today is going to be a good day");
quotes[1] = ("Tomorrow is going to rain");
quotes[2] = ("Next month will be blissful");
quotes[3] = ("You are very lucky to be here");
quotes[4] = ("The love of your life notices you");
}
WriteLine("Please enter a number between one and five");
response = Convert.ToInt32(ReadLine());
WriteLine(quotes[response]);
response is a number from 1 to 5. To get the array item (string quote) that corresponds to the response you need to evaluate quote[response-1]. This is because arrays are 0-based in C#. That means an array of 5 items is indexed with 0..4.
class Program
{
static void Main(string[] args)
{
string[] quotes = new string[]
{
"Today is going to be a good day",
"Tomorrow is going to rain",
"Next month will be blissful",
"You are very lucky to be here",
"The love of your life notices you"
};
int response;
int.TryParse(Console.ReadLine(), out response);
if (response>=1&&response<=quotes.Length)
{
Console.WriteLine(quotes[response-1]);
}
else
{
Console.WriteLine("Invalid input");
}
}
}
BTW, the question has nothing to do with passing parameters.

Array.ToString() returning System.Char[] c#

Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
code:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
output:
The output should say Word to guess: Hello.
Please will someone explain why this is happening as its not the first time I have run into this problem.
Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].
To convert a char[] to string you can use:
string s = new string(charArray);
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
The constructor public String(char c, int count) repeats c count times.
The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN
Returns a string that represents the current object.
In order you get a string from the characters in this array, you could use this:
Console.Write("Word to Guess: {0}" , new String(stars));
The correct way to do this would be:
string StarString = new string(stars);
ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.
Try this code:
static string ConvertCharArr2Str(char[] chs)
{
var s = "";
foreach (var c in chs)
{
s += c;
}
return s;
}

Save text data to array

I'm very new to working with C#. I am trying to save data (text such as a persons name) which is entered into the console and then 'read' to an array.
The name of the array i want to save data to is: name2convert
The variable collecting the data (name to be converted) is: nameEntered
Any help is very much appreciated. I've been working on this for a few hours and have done several searches, but i have not found any answers which I could understand with my limited understanding of C# at this time. I've only been trying to learn this for a few weeks - i'm very very green. Any help is appreciated.
Note: String names was my test array so that i could see that i knew how to read data back from an array.
I want to save the data to the names2Convert array.
This is my code:
using System;
namespace a061___String_Manipulations___PigLatin
{
///loop - ask for number of names equal to number asked
/// read line, save to array, iterate one up until num equals value asked for
class Program
{
//Arrays
String[] names = { "test01", "test02", "test03", "test04", "test05" }; //Test loop
String[] name2convert = new String[1];
//Variables & Ints?
string title = ">>>-- Welcome to the Highly Enlightening World of Igp-ay Atinl-ay --<<< \n";
string totalIs = "You said you want to convert a total of";
string listCommands = "Is that correct? If so type (Y)es, (R)enter or (Q)uit";// general commands used
string addSuffix ="-ah!"; // Add to end of each name
string nameEntered = "";//name to be converted
int namesTotal = 0;//
//Main Method
public void Play()
{
Console.WriteLine(title); //announce program
askTotal(); //ask number of names
while (true)
{
Console.WriteLine(listCommands);//lists options
String command = Console.ReadLine().ToLower();//reads user command
if (command == "y") // if askTotal true save to array? how?
{
askName();//collects name entered
confirmName();//allows user to confirm spelling, etc.
//y save the array nameEntered name2convert
//name2convert.Add(nameEntered);
name2convert[0] = nameEntered;
//confirm name
for (int i = 0; i < name2convert.Length; i++)
{
Console.WriteLine("Name Aquired: " + name2convert[i]);
}
}
else if (command == "r")
{
askName();//asks name
}
else if (command == "q")
{
Console.WriteLine("Cheers!"); break; //end
}
else
{
Console.WriteLine("Sorry. Invalid Request");//try again
}
PrintList();//test array
}
}
//Helper Methods
public void PrintList()//iterates through, prints names stored in array
{
Console.WriteLine("Print List");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine((i + 1) + ". " + names[i] + addSuffix);
}
}
//iterates through, prints names stored in array
public void askName()
{
Console.WriteLine("Enter Name: ");//Confirming
String nameEntered = Console.ReadLine().ToLower();// Capture name
Console.WriteLine("Name Captured: " + nameEntered);//confirming name caught
}
//iterates through, prints names stored in array
public void confirmName()
{
Console.WriteLine(listCommands);//Confirming
String command = Console.ReadLine().ToLower();
}
//how many names to convert
public void askTotal()
{
Console.WriteLine("How many names would you like to convert?");//Ask for content
namesTotal = int.Parse(Console.ReadLine());
Console.WriteLine(totalIs + " " + namesTotal);//Confirming
}
//Call Application
static void Main(string[] args)
{
Program StringManipulations = new Program();
StringManipulations.Play(); //Call forth the Pig Latin...
Console.Read();//
}
}
}
Change this:
//y save the array nameEntered name2convert
name2convert.Add(nameEntered);
To this:
name2convert[0] = nameEntered;
EDIT:
In askName() function change:
String nameEntered = Console.ReadLine().ToLower();// Capture name
To:
nameEntered = Console.ReadLine().ToLower();// Capture name
You already have nameEntered of type string declared as property of your class.
And why are you using string and then String? it's the same, as string is alias of String (which is in fact System.String in C#) - but be consistent!
As you already allocated the memory for this array (it's fixed size - in your case it's one).
So to access the first (and only) cell in your array, you should use name2convert[0] - 0 is the first index at any array and usually at any other struct/container in C# (and many other programming languages).
Another approach (as you were trying in your example) is to user List<String> instead.
For more information on arrays and Lists refer to here:
Array tutorial
List tutorial and examples
If you want save EVERY WORD that the user inputs use an List of Strings e.g
List<String> name2convert;
then
name2convert.Add(nameEntered);
to go through the list
foreach (String word in name2convert)
{
Console.WriteLine(word);
}

Assign values to a group of variables using recursion in C#?

How can I assign values to a group of variables using recursion in C#?
I can easily do it with a simple procedure, but I have no idea how to do it using recursion.
public void Assign()
{
Console.Write("Name: ");
Name = Console.ReadLine();
Console.Write("e-mail: ");
Email = Console.ReadLine();
Console.Write("Phone Number: ");
Phone = int.Parse(Console.ReadLine());
}
Thanks for the help.
If you're going to use recursion, you've got to have some sort of local context that's sufficient to accomplish whatever work you're going to do in your function, and you've got to know when / where to stop (and start popping your stack).
Your example looks like (if anything at all) a loop.
Your problem seems like homework because textbooks usually use this kind of horrible questions to teach recursion.
namespace Homework
{
class Recursion
{
static string[] nameList = new string[5];
static void Main(string[] args)
{
AssignNames(0);
Console.WriteLine("The names are:");
foreach(string name in nameList)
{
Console.WriteLine(name);
}
Console.ReadKey();
}
static void AssignNames(int index)
{
if (index == nameList.Length) return;
Console.Write("Enter name #{0}: ", index + 1);
nameList[index] = Console.ReadLine();
AssignNames(index + 1);
}
}
}

Reading values out from an ArrayList in an independent function

I am having troubling reading my values out of an ArrayList. The compiler goes into the ReadOutFromArray function, but skips the Console.WriteLine(st)? Can anyone tell me where I went wrong. Been on it for a couple of hours chasing my tail. Thanks.
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace BoolEx
{
class Program
{
static void Decision(ArrayList decis)
{
bool ans = true;
decis = new ArrayList();
//ArrayList aList = new ArrayList();
while (ans)
{
Console.WriteLine("1=True 0=False");
int x = Int32.Parse(Console.ReadLine());
if (x == 1)
{
ans = true;
}
else
{
ans = false;
}
if (ans == true)
{
ReadInArray(decis);
}
else
{
ReadOutArray(decis);
}
}
}
static void ReadInArray(ArrayList f)
{
f= new ArrayList();
Console.WriteLine("Enter in a name");
f.Add(Console.ReadLine());
}
static void ReadOutArray(ArrayList d)
{
d = new ArrayList();
ReadInArray(d);
foreach (string st in d)
{
Console.WriteLine(st);
}
}
static void Main(string[] args)
{
ArrayList g = new ArrayList();
Decision(g);
}
}
}
The problem is your ReadInArray method:
static void ReadInArray(ArrayList f)
{
f= new ArrayList();
Console.WriteLine("Enter in a name");
f.Add(Console.ReadLine());
}
In the first line of the method, you're basically saying, "I don't care what ArrayList reference was passed in - I'm going to overwrite the local variable f with a reference to a new ArrayList."
I suspect you meant something like this:
static void ReadInArray(ArrayList f)
{
f.Clear();
Console.WriteLine("Enter in a name");
f.Add(Console.ReadLine());
}
If you don't understand why that changes things, see my parameter passing article.
Other things you should consider:
If you're only going to read a single line, why not use something like this:
static string ReadNameFromUser()
{
Console.WriteLine("Enter in a name");
return Console.ReadLine();
}
The same sort of thing occurs elsewhere. Don't try to use collections for all your input and output. Returning a value is much clearer than populating a list which is passed into the method.
Given that you can obviously refer to generic collections (given your using directives) you should really consider using List<string> instead of ArrayList
Code like this:
if (x == 1)
{
ans = true;
}
else
{
ans = false;
}
... would be better written as
ans = (x == 1);
(The brackets are optional, but help readability.)
Code like this:
if (ans == true)
is better written as:
if (ans)
Although I do agree with everything Skeet has mentioned, it appears the poster is trying to understand some things and I think
Jon might have missed that.
First if all you want to do is fill a list and print it try this:
static void (main)
{
ArrayList l = new ArrayList();
FillMyList(l);
DisplayMyList(l);
}
public static void FillMyList(ArrayList temp)
{
for(int i = 0; i < 10; i++)
temp.Add(i);
}
public static void DisplayMyList(ArrayList temp)
{
foreach(int i in temp)
Console.WriteLine(i);
}
Second thing is take what Jon Skeet has mentioned and definately understand some things. Booleans are just true / false (unless you introduce the nullable types) but for now keep it simple.
ArrayList is really old school, it kind of suffers like the HashTable in that you can easily run into trouble adding different data types into the object (read up on boxing of data types and unboxing).
Finally, you should really replace anything with this System.Collection.ArrayList to System.Collections.Generic.List.
The list class is a generic class and is made available so that you don't have to deal with the issues that you could encounter when dealing with array lists or hash tables.
Edit
I noticed you were asking users to add items to the list. You can do this using a do while loop instead of the for loop I posted, something to this effect (note i have not tested any of this):
public static void FillMyList(ArrayList temp)
{
char c='y';
do {
Console.WriteLine("Enter a value");
int x = Int32.Parse(Console.ReadLine());
temp.Add(x);
Console.WriteLine("Continue adding numbers to list, if so type y");
char c = Console.ReadLine();
}while(c=='y' || c=='Y');
}
Again I am just giving you examples here, you will have to handle user input in case someone doesn't enter the correct information, exceptions, etc.

Categories

Resources