Call method with parameters - c#

I am working through learning C# on my own - this is not a homework assignment. I am only on chapter 7 so I am hoping for a simple/basic answer.
I am having troubles calling the TalentListing method from Main that gets its parameters from another method. Do I have to duplicate them in the Main method?
I realize the methods are void - I don't need them to return anything, I just need them to run.
Sorry the code is long, I thought it would be best to show it all.
Thank you!
class Program
{
static void Main()
{
int pastContestants;
int currentContestants;
// Call Methods:
Console.Write("LAST YEAR'S TALENT: ");
pastContestants = Contestants();
Console.Write("THIS YEAR'S TALENT: ");
currentContestants = Contestants();
Overview(pastContestants, currentContestants);
CompetitorTalents(currentContestants);
// need to call the TalentListing Method...
TalentListing(CompetitorTalents(contestantNames), CompetitorTalents(validTalentCodes), CompetitorTalents(contestantTalentCodes);
Console.ReadLine();
}
public static int Contestants()
{ // Get & returns valid # of contestants. Called twice - last year & this year
int contestants = 0; // holds return value
const int MIN = 0; // will allow 0 as an answer
const int MAX = 30; // will allow 30 as an answer
Console.Write("Please enter the number of contestants: ");
contestants = Int32.Parse(Console.ReadLine());
while (contestants < MIN || contestants > MAX)
{
Console.Write("Invalid number. Please enter a number between 0 and 30, inclusive: ");
contestants = Int32.Parse(Console.ReadLine());
}
return contestants;
}
public static void Overview(int past, int current)
{ // Accepts contestant - past & current. Displays 1 of 3 messages.
double entranceFee = 25.00;
Console.WriteLine("\nWe had {0} contestants last year and have {1} contestants this year.", past,
current);
//if more than double
if (current > (past * 2))
Console.WriteLine("The competition is more than twice as big this year!");
//if bigger but no more than double
if (current > past && current < (past * 2))
Console.WriteLine("The competition is bigger than ever!");
//if smaller than last year
if (current < past)
Console.WriteLine("A tighter race this year. Come out and cast your vote!");
Console.WriteLine("\nThe revenue expected for this year is {0:C}.", current * entranceFee);
}
public static void CompetitorTalents(int current)
{ // Fill array of competitors and their talent codes.
string[] contestantNames;
string contestantNameEntered;// user entry
char[] contestantTalentCodes;
char talentCodeEntered; // user entry
string[] talents = { "Dancing", "Musical", "Other" };
char[] validTalentCodes = { 'D', 'M', 'O' };
int[] total = new int[talents.Length];
bool validCode = false;
int counter = 0;
contestantNames = new string[current]; // set array size
contestantTalentCodes = new char[current]; // set array size
// put contestants in array
while (counter < current)// loop for all contestants
{
// get contenstants name and put in array
Console.Write("Please enter the name of contestant: ");
contestantNameEntered = Console.ReadLine();
counter += 1; // contestant number
validCode = false;
//place in correct array element
contestantNames[counter - 1] = contestantNameEntered;
// get contestants talent code, verify and place in array
while (validCode == false) // reset per contestant
{
Console.Write("Please enter the contestant's talent code (D=Dancing, M=Musical, O=Other): ");
talentCodeEntered = Char.Parse(Console.ReadLine().ToUpper()); // convert to uppercase
for (int x = 0; x < validTalentCodes.Length && !validCode; ++x)
if (talentCodeEntered == validTalentCodes[x]) // talent code valid?
{
validCode = true; // true if match found
contestantTalentCodes[counter - 1] = talentCodeEntered; //put talent code in array
x = validTalentCodes.Length; // breaks out of loop
}
if (validCode == false) // false if no match found = invalid code.
{
Console.WriteLine("Invalid code talent Code.");
}
}
}
// search all elements of validTalentCodes array (D, M, O), count instances in contestantTalentCodes array
for (int z = 0; z < validTalentCodes.Length; z++) // validTalentCodes
for (int x = 0; x < contestantTalentCodes.Length; x++) // contestantTalentCodes
if (contestantTalentCodes[x] == validTalentCodes[z])
{
total[z]++;
}
for (int x = 0; x < talents.Length; ++x)
Console.WriteLine("Total contenstants for {0} is {1}.", talents[x], total[x]);
}
public static void TalentListing(string contestantNames, char [] validTalentCodes, char [] contestantTalentCodes)
{ // Continuously prompt for talent codes and display contestants with the corresponding talent until quit.
// What talent code would you like to see (or QUIT)?
const char QUIT = 'Q';// must be upper as char are converted!!
char userOption = ' ';
bool validCode = false;
while (userOption != QUIT)
{
Console.Write("\nWhat talent code would you like to view? (D, M, O or Q to quit): ");
validCode = false; // reset from previous section
userOption = Char.Parse(Console.ReadLine().ToUpper());
for (int x = 0; x < contestantNames.Length && !validCode; ++x)
{
if (userOption == validTalentCodes[x]) // valid talent code?
{
validCode = true;
Console.Write("The contestants in {0} talent are: ", validTalentCodes[x]);
// display list of contestants with that code
for (int z = 0; z < contestantTalentCodes.Length; z++) // validTalentCodes
if (contestantTalentCodes[z] == userOption)
{
Console.Write("\n{0}", contestantNames[z]);
}
}
}
if (validCode == false)
Console.WriteLine("Invalid talent code!");
}
Console.WriteLine(); // when QUIT is selected
}
}

The CompetitorTalents(int current) method has no return value, you are using void. The TalentListing receives two strings. So you need to get those two from somewhere. If you want them to come from the CompetitorTalens method, you have to change it so it returns string and actually return something from it.

For this simple app use static global variables. Just copy this code and take a look.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static string[] talents = { "Dancing", "Musical", "Other" };
public static char[] validTalentCodes = { 'D', 'M', 'O' };
public static string[] contestantNames;
public static char[] contestantTalentCodes;
static void Main()
{
int pastContestants;
int currentContestants;
// Call Methods:
Console.Write("LAST YEAR'S TALENT: ");
pastContestants = Contestants();
Console.Write("THIS YEAR'S TALENT: ");
currentContestants = Contestants();
Overview(pastContestants, currentContestants);
CompetitorTalents(currentContestants);
// need to call the TalentListing Method...
TalentListing();
Console.ReadLine();
}
public static int Contestants()
{ // Get & returns valid # of contestants. Called twice - last year & this year
int contestants = 0; // holds return value
const int MIN = 0; // will allow 0 as an answer
const int MAX = 30; // will allow 30 as an answer
Console.Write("Please enter the number of contestants: ");
contestants = Int32.Parse(Console.ReadLine());
while (contestants < MIN || contestants > MAX)
{
Console.Write("Invalid number. Please enter a number between 0 and 30, inclusive: ");
contestants = Int32.Parse(Console.ReadLine());
}
return contestants;
}
public static void Overview(int past, int current)
{ // Accepts contestant - past & current. Displays 1 of 3 messages.
double entranceFee = 25.00;
Console.WriteLine("\nWe had {0} contestants last year and have {1} contestants this year.", past,
current);
//if more than double
if (current > (past * 2))
Console.WriteLine("The competition is more than twice as big this year!");
//if bigger but no more than double
if (current > past && current < (past * 2))
Console.WriteLine("The competition is bigger than ever!");
//if smaller than last year
if (current < past)
Console.WriteLine("A tighter race this year. Come out and cast your vote!");
Console.WriteLine("\nThe revenue expected for this year is {0:C}.", current * entranceFee);
}
public static void CompetitorTalents(int current)
{ // Fill array of competitors and their talent codes.
string contestantNameEntered;// user entry
char talentCodeEntered; // user entry
int[] total = new int[talents.Length];
bool validCode = false;
int counter = 0;
contestantNames = new string[current]; // set array size
contestantTalentCodes = new char[current]; // set array size
// put contestants in array
while (counter < current)// loop for all contestants
{
// get contenstants name and put in array
Console.Write("Please enter the name of contestant: ");
contestantNameEntered = Console.ReadLine();
counter += 1; // contestant number
validCode = false;
//place in correct array element
contestantNames[counter - 1] = contestantNameEntered;
// get contestants talent code, verify and place in array
while (validCode == false) // reset per contestant
{
Console.Write("Please enter the contestant's talent code (D=Dancing, M=Musical, O=Other): ");
talentCodeEntered = Char.Parse(Console.ReadLine().ToUpper()); // convert to uppercase
for (int x = 0; x < validTalentCodes.Length && !validCode; ++x)
if (talentCodeEntered == validTalentCodes[x]) // talent code valid?
{
validCode = true; // true if match found
contestantTalentCodes[counter - 1] = talentCodeEntered; //put talent code in array
x = validTalentCodes.Length; // breaks out of loop
}
if (validCode == false) // false if no match found = invalid code.
{
Console.WriteLine("Invalid code talent Code.");
}
}
}
// search all elements of validTalentCodes array (D, M, O), count instances in contestantTalentCodes array
for (int z = 0; z < validTalentCodes.Length; z++) // validTalentCodes
for (int x = 0; x < contestantTalentCodes.Length; x++) // contestantTalentCodes
if (contestantTalentCodes[x] == validTalentCodes[z])
{
total[z]++;
}
for (int x = 0; x < talents.Length; ++x)
Console.WriteLine("Total contenstants for {0} is {1}.", talents[x], total[x]);
return ;
}
/// Continuously prompt for talent codes and display contestants with the corresponding talent until quit.
/// What talent code would you like to see (or QUIT)?
public static void TalentListing()
{
const char QUIT = 'Q';// must be upper as char are converted!!
char userOption = ' ';
bool validCode = false;
while (userOption != QUIT)
{
Console.Write("\nWhat talent code would you like to view? (D, M, O or Q to quit): ");
validCode = false; // reset from previous section
userOption = Char.Parse(Console.ReadLine().ToUpper());
for (int x = 0; x < contestantNames.Length && !validCode; ++x)
{
if (userOption == validTalentCodes[x]) // valid talent code?
{
validCode = true;
Console.Write("The contestants in {0} talent are: ", validTalentCodes[x]);
// display list of contestants with that code
for (int z = 0; z < contestantTalentCodes.Length; z++) // validTalentCodes
if (contestantTalentCodes[z] == userOption)
{
Console.Write("\n{0}", contestantNames[z]);
}
}
}
if (validCode == false)
Console.WriteLine("Invalid talent code!");
}
Console.WriteLine(); // when QUIT is selected
}
}
}

You need to close the method call (So you were missing a ) at the end) :
TalentListing(CompetitorTalents(contestantNames), CompetitorTalents(validTalentCodes), CompetitorTalents(contestantTalentCodes));
The methods you are calling are void meaning they dont return anything:
public static string CompetitorTalents(int current)
Then in the method call for the CompetitorTalents you should pass in what is the method needs. I would advise doing this on separate lines:
string contestantNames = CompetitorTalents(currentContestants);
And so on, then in the TalentListing you could just reference the individual variables:
TalentListing(contestantNames, validTalentCodes, contestantTalentCodes);

Well, looking at your method signatures we can see the following:
void TalentListing(string, char[], char[])
void CompetitorTalents(int)
Your CompetitorTalents method returns a void, but you are trying to pass the result of that method as parameters for your TalentListing method. So you are essentially trying to call TalentListing(void, void, void), when really it wants a string, a char[], and then another char[]

Related

Write a program that determines whether two or more consecutive numbers are equal

Write a program that determines whether, in a sequence of N numbers entered by the user, if two or more consecutive numbers are equal. Print out, if any, the position of the first elements of the sequence of equal numbers.
This is what i got so far but it isn't working for some reason. What am I doing wrong?
using System;
public class Exercises
{
static void Main()
{
Console.WriteLine("Insert the length of the sequence of numbers:");
int n = Convert.ToInt32(Console.ReadLine());
List<int> seq = new List<int>();
int equalSeqStart = -1;
for (int i = 0; i < n; i++)
{
Console.WriteLine("Insert the number in position" + (i + 1) + ":");
seq.Add(i);
if ((seq[i] == seq[i - 1]) && (equalSeqStart == -1))
{
equalSeqStart = i - 1;
}
}
if (equalSeqStart != -1)
{
Console.WriteLine("The sequence of equal numbers starts at" + (equalSeqStart));
}
else
{
Console.WriteLine("There is no sequence of equal numbers");
}
}
}
All you have to do is to compare prior item with current one; you have no need in collections:
static void Main() {
Console.WriteLine("Insert the length of the sequence of numbers:");
//TODO: int.TryParse is a better choice
int n = int.Parse(Console.ReadLine());
int equalSeqStart = -1;
for (int i = 0, prior = 0; i < n; ++i) {
Console.WriteLine($"Insert the number in position {i + 1}:");
//TODO: int.TryParse is a better choice
int current = int.Parse(Console.ReadLine());
if (i > 0 && equalSeqStart < 0 && current == prior)
equalSeqStart = i;
prior = current;
}
if (equalSeqStart != -1)
Console.WriteLine($"The sequence of equal numbers starts at {equalSeqStart}");
else
Console.WriteLine("There is no sequence of equal numbers");
}

Alternating Odd Even or Even Odd in C#

I've created a program that adds all input values from the user and prints the sum if the user entered 0 or greater than 101. Here's my code:
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
I'm trying to figure how to accepts numbers alternately. For example, Input values are: 4, 7, 8, 3, 6, 1. If the user input two consecutive odd or even number the system will not accept two consecutive odd or even or it will display the sum of all inputted numbers.
Taking the recomendation of Andrew an Peter you can add the list to save your previous inputs and do some checks to the current and prev data to do the logic.
the code that implements this is the following:
//save input list
List<int> inputNumbers = new List<int>();
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
//My Recomendation ==============================
//save previus input numbers
inputNumbers.Add(n);
//Check is there are previous input number
if(inputNumbers.Count>1){
//New control vars
Boolean previousNumberIsOdd= false,currentNumberIsOdd= false;
foreach (int item in inputNumbers)
{
Console.Write(item+",");
}
//check if previus number is odd
if((inputNumbers[inputNumbers.Count-2])%2 == 0){
previousNumberIsOdd = true;
}
//Check if current number is odd
if(n%2==0){
currentNumberIsOdd = true;
}
Console.WriteLine("Control vars:" + previousNumberIsOdd +"/"+currentNumberIsOdd);
//Check diferent scenarios and do the logic
//previous and current number are odds
if(previousNumberIsOdd && currentNumberIsOdd){
//break while and write the result
break;
}
//previous and current number are evens
if(!previousNumberIsOdd && !currentNumberIsOdd){
//break while and write the result
break;
}
}
//if there aren't numbers to break the cycle then do the original logic
//End of my recomendation =====================
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
}
You can do many optimizations to this code but a put it like that to be very clear in the logic.
By using two flag you can achieve the result.
int n, sum = 0;
bool previous = false, current;
bool init = true;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
current = n % 2 == 0;
if( current == previous && !init)
break;
previous = current;
init = false;
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
Output

How find average of numbers(by input) and also count numbers

I mean how to count and sum input numbers until receive "end".
thanks !
And also how to find out input is number or letter in c#?
class Program
{
static void Main(string[] args)
{
int n = 0;
int sum = 0;
string inp;
do
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num= Convert.ToInt16(inp);
sum = sum + num;
n++;
} while (too == "end");
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
}
}
I would suggest you use a normal while loop and also add validation to check to integer input.
For the while loop you want to loop until the input is not equal to "end":
while(inp != "end")
For the validation, you can use int.TryParse method:
int num = 0;
if (int.TryParse(inp, out num)) { }
Here is a modified example of your code:
int n = 0;
int sum = 0;
string inp = null;
while(inp != "end")
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num = 0;
if (int.TryParse(inp, out num))
{
sum = sum + num;
n++;
}
}
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
// A list to hold all of the numbers entered
List<int> numbers = new List<int>();
// Will hold the inputted string
string input;
// This needs to be outside the loop so it's written once
Console.Write("Numbers: " + Environment.NewLine);
// Keep going until we say otherwise
while (true)
{
// Get the input
input = Console.ReadLine();
// Will hold the outcome of parsing the input
int number = -1;
// Check to see if input was a valid number
bool success = int.TryParse(input, out number);
// If it was a valid number then remember it
// If ANY invalid or textual input is detected then stop
if (success)
numbers.Add(number);
else
break;
}
// Write the count and average
Console.WriteLine("Count:" + numbers.Count);
Console.WriteLine("Average:" + numbers.Average());
Console.ReadLine();
Input:
Numbers:
1
2
3
4
5
Output:
Count: 5
Average: 3
The only thing here a little different to what you specified is ANY invalid or textual entry causes it to finish, not just typing the word "end", although that obviously works too.

Sum integers using a loop c#

I am new to programming and I think I have confused myself I'm trying to make a loop that asks users for integers when the user inputs a integer greater than 100 then the console displays the amount of integers the user has input and the sum of these integers. I know it's basic but I can't figure where I went wrong.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum1, strNum2;
int num1, num2;
int i = 0;
int sum =0 ;
Console.WriteLine("Please enter a integer between 1 and 100"); // asks for user input
strNum1 = Console.ReadLine();
num1 = int.Parse(strNum1);
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum2 = Console.ReadLine();
num2 = int.Parse(strNum2); //input is stored as num2
sum = num2; //store num2 in sum
i++;
if (num2 >= 100) // if num2 int is greater than 100
{
sum = (num1 +num2 +sum); // do calculation
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
while (i < 100);
}
}
}
any help would be appreciated thanks everyone!
You're on the right track... a couple of things:
Do... While is used when you always want to run through the block at least once, so your first 'get' from the user can be inside the block. You can code whatever you want to happen after the condition fails right after the block, instead of checking the same condition inside it.
Make sure if you're simply using Parse that you wrap it in a try...catch, because your user could type in anything (not just numbers). Personally I usually use TryParse instead.
Finally, make sure you're comparing to the correct variable. Checking that i < 100 will keep looping until 100 numbers have been entered; you want to compare the user's input instead.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string prompt = "Please enter {0} integer between 1 and 100";
string strNum;
int num = 0;
int i = 0;
int sum =0 ;
do //ask once and repeat while 'while' condition is true
{
string pluralPrompt = i > 0 ? "another" : "an";
prompt = string.Format(prompt,pluralPrompt);
Console.WriteLine(prompt); // asks for user input
strNum = Console.ReadLine();
if (!Int32.TryParse(strNum, out num)) //input is stored as num
{
// warn the user, throw an exception, etc.
}
sum += num; //add num to sum
i++;
}
while (num < 100);
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
}
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum;
int num;
int i = 0;
int sum = 0;
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum = Console.ReadLine();
if (int.TryParse(strNum, out num)) //input is stored as num2
{
if (num < 101)
{
i++;
sum += num;
continue;
}
else
{
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
break;
}
}
}
while (i < 100);
}
}

Index out of Range exception in C# when iterating through an array

I have this code I'm using to create a program that takes a a range and outputs to the Console the prime numbers. I have one problem, I'm trying to iterate through the array I built so the loop should only write to the console the values that are prime using my method's return value. The problem I'm having is that I have the second condition set to numArray.Length but it seems to give me the Index out of Range Exception. I just want the loop to iterate through all values in the numArray and stop when it's done figuring out whether the last value is prime or not.
public struct Prime
{
public int x;
// constructor for Prime
public Prime(int x1)
{
x = x1;
}
public int IsPrime(int number)
{
int i;
for (i = 2; i * i <= number; i++)
{
if (number % i == 0) return 0;
}
return 1;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an Integer");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a Second Integer of Greater Value");
// int num2 = 0;
int num2 = Convert.ToInt32(Console.ReadLine());
/* if (num2temp > num1)
{
num2temp = num2;
}
else
{
Console.WriteLine("You Did Not Enter An Integer Greater Than the First Integer, Please Enter Your Integers Again.");
Environment.Exit(0);
}
*/ int index = 1;
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
Console.WriteLine("value: {0}", numArray[40]);
/* Prime myprime = new Prime();
if (myprime.IsPrime(numArray[12]) == 1)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("False");
} */
Prime myprime = new Prime();
int value = 0;
for (int y = 1; y <= num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
You're currently trying to iterate up to and including the size of the array. Arrays are 0-indexed in C#. So this:
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
should be:
for (int i = num1; i < num2; i++)
And note that to get at the first element array, num1 would have to be 0, not 1.
Likewise, your initial assignment of index as 1 should be 0 instead. Basically you need to go through all your code (it's confusing at the moment with lots of bits commented out) and check everywhere that you're assuming arrays are 1-based, and instead change your code as they're 0-based.
(In some cases you may just want to make the array one bigger, of course. If you want an array which logically contains the values 1 to x inclusive, you can either create an array of size x and subtract one from each index all the time, or create an array of size x + 1.)
Your index starts from 1 but should start from 0:
int index = 0; //CHANGE HERE
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
and then here y should also be 0 and check should if it is less than num2:
for (int y = 0; y < num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
because array indexing in C# start from 0.

Categories

Resources