How to address 3 parameters in my method program? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to write a C# code for the problem written below, but whatever I do, I can't figure out how to solve the problem. I guess I can't understand why it should be done the way it is asked! Anyways, this is what I need to do: Start a new console application.
In the Main method, Create a string array of size 5, name the array
Profile. Ask the user to input their first name, But you must do
that by calling a method you will write called GetStringInput This
method should require 3 parameters.
The first is a string, which is the question to ask the user. (For this first usage, you might pass in a string that says "enter your first name")
The second parameter is the Profile array
The third parameter is an int, the index, meaning, in which location in the array the user's answer should be stored.
First question (First name).
Ask the user for their last name, again, by calling that same GetStringInput, but passing in a different question.
Ask the user for their age, again, by calling that same GetStringInput,
but passing in a different question (note that the age will be entered and stored as a string, and not converted to an int)
Ask the user for their favorite color, again, by calling that same GetStringInput, but passing in a different question.
Ask the user for their favorite sport, again, by calling that same GetStringInput, but passing in a different question.
Now call a new method called DisplayProfile. This method should require a string array as a parameter, and you will pass in the Profile array. Add a Console.ReadLine(); statement and your Main method is done.
Now implement the 2 methods that you have been calling, GetStringInput and DisplayProfile. The DisplayProfile method should pull the information out of the array, and write out the values in a reasonable way.
Something like, for example Your name is John Smith, you are 21 years old. Your favorite color is green and your favorite sport is tennis.
Now, I have written this code:
static void Main(string[] args)
{
string[] Profile = new string[5];
GetUserInput(Profile);
DisplayProfile(Profile);
}
private static void DisplayProfile(string[] Showrofile)
{
Console.WriteLine("Your name is {0} {1}, you are {2} years old.\nYour favorite color is {3} and your favorite sport is {4}.",
Showrofile[0], Showrofile[1], Showrofile[2], Showrofile[3], Showrofile[4]);
}
public static string [] GetUserInput(string[] Getprofile)
{
string[] Question = new string[5];
Question[0] = "Enter your First name:";
Question[1] = "Enter your Last name:";
Question[2] = "Enter your Age:";
Question[3] = "Enter your Favorite color:";
Question[4] = "Enter your Favorite sport:";
for (int i = 0; i < Question.Length; i++)
{
Console.WriteLine(Question[i]);
Getprofile[i] = Console.ReadLine();
}
return Getprofile;
}
}
}
I don't know what to do. I appreciate your help!

I have been watching the comments and the other people are right, you should read how to ask the question because it wasn't clear. It does seem some simple Google searches would have answered this question very easily but I will take pity on your hair pulling. Here is an example of what you are asking for.
Sometimes the best approach is to walk away and then come back calm because when you were asking the Gabe how to make a method with three parameters you pretty much answered your own question. See below and good luck, take it slow.
public static void Main()
{
const int TOTAL_QUESTIONS = 5;
string[] profile = new string[TOTAL_QUESTIONS];
string[] questions = new string[]
{
"Enter your First name:",
"Enter your Last name:",
"Enter your Age:",
"Enter your Favorite color:",
"Enter your Favorite sport:"
};
for (int i = 0; i < TOTAL_QUESTIONS; i++)
{
profile = GetUserInput(questions[i], profile, i);
}
DisplayProfile(profile);
}
private static void DisplayProfile(string[] profile)
{
Console.WriteLine($"Your name is {profile[0]} {profile[1]}, you are {profile[2]} years old.\nYour favorite color is {profile[3]} and your favorite sport is {profile[4]}.");
}
//Here is where you put the parameters you told Gabe about.
private static string[] GetUserInput(string question, string[] profile, int index)
{
Console.WriteLine(question);
profile[index] = Console.ReadLine();
return profile;
}
Edit:
Since you brought it up in the comments about the teacher saying GetUserInput doesn't need to return anything you can see how it works. It would look like this.
public static void Main()
{
const int TOTAL_QUESTIONS = 5;
string[] profile = new string[TOTAL_QUESTIONS];
string[] questions = new string[]
{
"Enter your First name:",
"Enter your Last name:",
"Enter your Age:",
"Enter your Favorite color:",
"Enter your Favorite sport:"
};
for (int i = 0; i < TOTAL_QUESTIONS; i++)
{
GetUserInput(questions[i], profile, i);
}
DisplayProfile(profile);
}
private static void DisplayProfile(string[] profile)
{
Console.WriteLine($"Your name is {profile[0]} {profile[1]}, you are {profile[2]} years old.\nYour favorite color is {profile[3]} and your favorite sport is {profile[4]}.");
}
private static void GetUserInput(string question, string[] profile, int index)
{
Console.WriteLine(question);
profile[index] = Console.ReadLine();
}

Related

I get an error when running this program in C#: no overload for method 'Movies' takes '0' arguments. I need a method that does it [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 2 years ago.
Improve this question
I want a method that gets input from the user, loops through the input, sorts the words that the user entered, and prints them sorted. (by the way, the language is c#). When I run the program, I get an error:
no overload for method 'Movies' takes '0' arguments"
there is the Main method but I couldn't put that in the code because StackOverflow will give me an error. the main method calls the method written below like this: Movies();
note: I am young and new to programming.
I know that I could do it just using the main method but I wanted to see what happens if I did that.
using System;
favoriteMovies = new string[4];
Console.WriteLine("Enter four movies: ");
for (int i = 0; i < favoriteMovies.Length; i++)
{
favoriteMovies[i] = Console.ReadLine();
}
Console.WriteLine("Here are the movies sorted alphabetically: ");
Array.Sort(favoriteMovies);
for (int i = 0; i < favoriteMovies.Length; i++)
{
Console.WriteLine(favoriteMovies[i]);
}
return favoriteMovies;
}
Since you don't show us more of your code, it is hard to guess where the error is. But I guess you write public static string[] Movies(var argument) instead of public static string[] Movies()
Here is what it would need to look like:
using System;
namespace Program{
class Program{
public static void Main(string[] args){
Movies();
}
public static string[] Movies(){
var favoriteMovies = new string[4];
Console.WriteLine("Enter four movies: ");
for (int i = 0; i < favoriteMovies.Length; i++)
{
favoriteMovies[i] = Console.ReadLine();
}
Console.WriteLine("Here are the movies sorted alphabetically: ");
Array.Sort(favoriteMovies);
foreach (string i in favoriteMovies)
{
Console.WriteLine(i);
}
return favoriteMovies;
}
}
}
I hope this will help you!
If not, please clarify your question!

CS1061: Type `string' does not contain a definition for `classChoice' and no extension method `classChoice' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to return the value of the string classChoice to a separate Class so that I can return the person's selection, I am still learning C# and have tried to understand this better i read that it needs an instance to work so i created 1, either way, i have tried about 8 different ways of doing this and all keep returning errors, what am I doing wrong?
made it a void and failed, took out the argument and tried to call only the property, tried it outside the cs file in the main cs still no luck.
public class Selection
{
public string CharSel(string classChoice = "")
{
Console.WriteLine("Welcome to the world of Text Games!");
Console.WriteLine("To begin you must select a class!");
Console.WriteLine("Lucky for you there is only 1 class to choose from at this time :-) ");
Console.WriteLine("Select a Class:");
Console.WriteLine("1. Wizard");
Console.WriteLine("2. Nothing");
Console.WriteLine("3. Nothing");
Console.WriteLine("4. Nothing");
Console.WriteLine("5. Nothing");
Console.Write("Make your selection: ");
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
{
classChoice = "Wizard";
Console.WriteLine("Congrats on selecting {0} now onto your adventure!", classChoice);
}
return classChoice;
}
}
public class Character
{
public static string Wizard(string name)
{
Selection s = new Selection();
string classChosen = s.CharSel().classChoice;
Console.WriteLine("Test, You are a {0}", classChosen);
name = "none yet";
return name;
}
}
Console should spiit out
Test, You are a Wizard
You have a syntax error in your program on the line:
string classChosen = s.CharSel().classChoice;
It should be:
string classChosen = s.CharSel();
CharSel() is a method which returns a string containing the value selected by the user.
You returned that string at the end of the method so when you call that method it effectively is the returned string (the value contained in the classChoice variable). That is why is is giving you that error: 'CharSel()' is a string and what you have written (s.CharSel().classChoice) is attempting to find a classChoice method on the String class (or an extension method). Just remove .classChoice from the assignment to classChosen and it will work as you expect.
Another important point is that classChoice is a private variable of the CharSel() method and isn't visible outside of the method.

Passing String Arrays to Functions? [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 5 years ago.
Improve this question
I'm not sure what I'm doing wrong. I'm trying to pass the array people to the function getInformation and have it so stuff (eventually it will ask for the names of people and their salaries but I can't seem to get the function to take the array as a parameter?
using System;
class SalesPeeps {
string[] people = new string[8];
double[] salaries = new double[8];
static void Main() {
getInformation(people);
}
static void getInformation(string[] arr) {
int i = 0;
do {
Console.WriteLine("Please input a the sales person's last name.");
i++;
} while (i < people.Length);
}
}
1) string[] people = new string[8];
is a field - not local variable. so when you say people - you are actually mean this.people but in static method there is no this.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
2) getInformation method use arr array as a parameter but do not reference to it. You can use people and make it static this will also fix problem from point 1.
I think this can be corrected this way:
class SalesPeeps
{
static string[] people = new string[8];
static double[] salaries = new double[8];
static void Main()
{
getInformation();
}
static void getInformation()
{
int i = 0;
do
{
Console.WriteLine("Please input a the sales person's last name.");
i++;
} while (i < people.Length);
}
}
You cannot access non-static field people from static method Main. Change its declaration to:
static string[] people = new string[8];
Both of your variables are class members, which means they are the variables of the objects you can create from the class SalesPeeps.
Your method getInformation() is a static method and therefore only accepts static inputs.
A fix for this would be to make both of your variables static. Read more here.
Either way, you should be getting a error message from the compiler and this question should not be necessary as there are plenty of resources on this topic. Just check your compiler errors in your IDE and google them.

Modify the last letters of words? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to code a program, which changes the last two (or just the last) letter(s) of the inputted word because of some weird grammar rules of the Lithuanian language.
For example, my name is Kazys.
I want a code which could change the last two letters (ys) to another letter (y).
So when a person inputs
Kazys
The output would be
Hello, Kazy.
If a person inputs Balys, the code should change the name to Baly and print it.
I am just a beginner in C#. So, I don't even know some of the basic functions.
Any help is very appreciated!!
P.S. For those who wonder, why do I need this, I can tell you that it's a thing in Lithuanian grammar which requires to change the end of the word if you are addressing somebody.
I, personally, think language rules like this are why regular expressions exist. It allows you to easily make rules with look-aheads, look-behinds, etc., to make sure that the word is only changed if it fits a certain structure. For your example case, it should be as easy as:
var firstName = "Kazys";
var formattedFirstName = Regex.Replace(firstName, #"ys$", "y");
The $ at the end of the string means that it will only change "ys" to "y" when "ys" are the last two letters in a string.
Regular Expressions can get much more complicated and many people don't like them. However, I find them to be concise and clear most of the time.
You can write an extension class that applies the rules stored in a dictionary easy enough. Complicated rules could make Regex a better option, but if simple string replacement, a case insensitive dictionary could be better to avoid checking every possible rule every time.
public static class LanguageExtensions
{
// Define case insentive dictionary
public static Dictionary<string, string> Rules = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
// List rules here
{ "ys", "y"},
};
public static string ApplyRules(this string input)
{
string suffix;
if (input != null && input.Length > 2 && Rules.TryGetValue(input.Substring(input.Length - 2, 2), out suffix))
return input.Remove(input.Length - 2) + suffix;
else
return input;
}
}
Then, you just have to call the extension method:
Console.WriteLine("Kazys".ApplyRules()); // "Kazy"
Minimal working sample of what you might be after.
You seem to have complex requirements to code but, this is the basic concepts of replacing string(s) within a string.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ChangeLastChar_46223845
{
public partial class Form1 : Form
{
TextBox txtbx_input = new TextBox();
TextBox txtbx_result = new TextBox();
Button btn = new Button();
public Form1()
{
InitializeComponent();
AddOurStuffToTheForm();
PutDefaultWordInInputBox();
}
private void PutDefaultWordInInputBox()
{
txtbx_input.Text = "Krazys";
}
private void AddOurStuffToTheForm()
{
txtbx_input.Location = new Point(5, 5);
btn.Location = new Point(5, txtbx_input.Location.Y + txtbx_input.Height + 5);
txtbx_result.Location = new Point(5, btn.Location.Y + btn.Height + 5);
btn.Text = "Substring";
btn.Click += Btn_Click;
this.Controls.Add(txtbx_input);
this.Controls.Add(btn);
this.Controls.Add(txtbx_result);
}
private void Btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtbx_input.Text) || string.IsNullOrWhiteSpace(txtbx_input.Text))
{
return;
}
if (txtbx_input.Text.EndsWith("ys"))
{
txtbx_result.Text = "Hello " + txtbx_input.Text.Substring(0, txtbx_input.Text.Length - 1);
}
}
}
}

Designing a simple console trivia application

We have been tasked with designing a C# trivia application as a File I/O exercise. So far, I've got a good start, but the presentation step is kind of stumping me.
I'm starting with a delimited file featuring the following data:
Question;CorrectAnswerA;AnswerB;AnswerC;AnswerD;AnswerExplanation
e.g.,
What color is the sky?;Blue;White;Green;Yellow;The sky is blue.
The game will display the question and the four answers from which the user can select.
What Color is the Sky?
A. Blue
B. White
C. Green
D. Yellow
Select A, B, C, or D:
Unfortunately, for ease of populating the dataset, A is always the correct answer. I want to randomize the order in which the four answers display, but the program still needs to know which was the correct answer. I also need to have a user input of A, B, C, or D tie back to a specific instance of an answer to compare the selectedAnswerString to the correctAnswerString.
I've been playing with an array of the four answers which are randomly populated, but I can't wrap my head around how to flag something as correct based on the user's choice; my logic to do or assign that always seems to fall out of scope or duplicate across all four records in the array.
Other students I've talked to said they created their datasets with the answers pre-scrambled (so they can just print them in the order read) with a FIFTH answer field for the correct answer. While definitely an EASY way to make it happen, I don't think it's as elegant as my strategy.
Should I just change the input dataset? does anyone have any ideas on a good way to pursue my idea for the randomization?
Create a class called Question with properties: int Id, string QuestionText, List<string> Answers, string CorrectAnswer
Or, as step forward, also create class Answer with Id and Value and reference to it.
public class Question
{
public int Id;
public string QuestionText;
public List<Answer> Answers;
public Answer CorrectAnswer;
}
public class Answer
{
public int Id;
public string Value;
}
Afterwards populate this structure and randomize when printing
Keep track of the correct answer using a separate variable. Then use Fisher-Yates to shuffle your array:
Random random = new Random();
void Shuffle(string[] answers) {
for (int i = 0; i < answers.Length - 1; i++) {
int j = random.Next(i, answers.Length);
string temp = answers[j];
answers[j] = answers[i];
answers[i] = temp;
}
}
After the user responds, just compare their selection with the correct answer you've saved.
Try defining your data structure for a question in this way:
public class Question
{
public string Question;
public string[] Answers;
public int CorrectAnswer;
public string CorrectAnswerExplanation
}
This way you can scramble the strings in the array Answers, while still keeping track of the index of the correct answer in CorrectAnswer.
Alternatively if you can't use a separate class to model the question (this is a homework question so maybe you have not learned this yet), you can use a predetermined position in the array (the 1st or the 5th element) to hold the index of the correct answer. So your array for answers would look like:
"Blue", "White", "Green", "Yellow", "0"
Step 1: Define a data structure. Others have already given you a structure so use that.
Step 2: Populate your data structure. You could System.IO.File.ReadLines and parse each line - I assume you have this bit handled already.
Step 3: Randomize the order of your answers. For this, assuming you have your structure:
public static void RandomiseAnswers(IEnumerable<Question> questions)
{
var rand = new Random((int)DateTime.Now.Ticks);
foreach (var question in questions)
{
question.Answers = question.Answers.OrderBy(x => rand.Next()).ToArray();
}
}
Step 4: Recieve gold star from teacher for your outstanding work
Personally I'd put a boolean in the Answer class defaulting to false. This way when the answer is selected you can read whether it's correct or not.
public class AskQuestion
{
public int Id;
public string Question;
public string Explanation;
public List<Answer> Answers = new List<Answer>();
}
public class Answer
{
public bool Correct = false;
public string Value;
}
now when you randomize the list the correct answer is automatically identified
One way to use these classes would be like this:
static void Main(string[] args)
{
StreamReader sr = new StreamReader("text.txt");
List<AskQuestion> Questions = new List<AskQuestion>();
Random rnd = new Random(DateTime.Now.Millisecond);
//Loop through the file building a list of questions
while(!sr.EndOfStream)
{
AskQuestion NewQuestion = new AskQuestion();
string[] input = sr.ReadLine().Split(';');
NewQuestion.Question = input[0];
NewQuestion.Explanation = input[5];
for(int i = 1; i < 5; i++)
{
Answer NewAnswer = new Answer();
NewAnswer.Value = input[i];
NewQuestion.Answers.Add(NewAnswer);
}
//The first question is always correct so set its boolean value to true;
NewQuestion.Answers[0].Correct = true;
//Now ranmdomize the order of the answers
NewQuestion.Answers = NewQuestion.Answers.OrderBy(x => rnd.Next()).ToList();
Questions.Add(NewQuestion);
}
//Generate menu and get response for each question
foreach(AskQuestion q in Questions)
{
Console.WriteLine(q.Question + ":\n\tA - " + q.Answers[0].Value + "\n\tB - " + q.Answers[1].Value + "\n\tC - " + q.Answers[2].Value + "\n\tD - " + q.Answers[3].Value + "\n");
char input = '0';
while(input < 'A' || input > 'D')
{
input = char.ToUpper(Console.ReadKey().KeyChar);
if(input >= 'A' && input <= 'D')
{
//Use the boolean value in the answer to test for correctness.
if(q.Answers[input - 'A'].Correct)
{
Console.WriteLine("\nCorrect\n");
}
else
Console.WriteLine("\nWrong\n");
Console.WriteLine(q.Explanation);
}
}
}
Console.ReadLine();
}

Categories