So I am having problems with programming a bowling application in c# to calculate 5 different scores, storing them in an array and returning the average, highest and lowest scores, I am having problems with the code for storing the array and returning the scores. Here is what i have so far:
static void Main(string[] args)
{
//Declarations
const double MIN_SCORE = 0;
const double MAX_SCORE = 300;
const int SCORE_COUNT = 5;
int[] scores = new int[SCORE_COUNT]; //stores all the scores
int inputScore; //stores one score
double total = 0; //to total the scores for average
double average; //average the grades
double highScore; //highest score of the games
double lowScore; //lowest score of the games
//INPUT
//loop to get scores
for (int bowler = 0; bowler < scores.Length; bowler++)
{
try
{
//prompt for and get the input
Console.Write("Please enter score for game " + (bowler + 1) + ":");
inputScore = Convert.ToInt16(Console.ReadLine());
//valid range?
if (inputScore > MAX_SCORE || inputScore < MIN_SCORE)
{
Console.WriteLine("Scores must be between " + MIN_SCORE +
" and " + MAX_SCORE + ". Please try again. ");
bowler--;
}
else
{
scores[bowler] = inputScore;
}
}
catch (Exception myEx)
{
Console.WriteLine(myEx.Message + " Please try again. ");
bowler--;
}
//PROCESS
Array.Sort(scores);
//OUTPUT
Console.WriteLine("\n\nAverage Score for Bowler:{0}");
}
}
Add this using statement:
using System.Linq;
Then you can use:
scores.Average();
scores.Max();
scores.Min();
Simple enough.
Related
i'm a beginner to c#,so i was trying to make a program that rolls a die for you and the enemy for 10 turns,each turns adding the number of your roll to an overall count and whoever got the largest in the end won,i didn't finish it all the way but this is what i have so far:
namespace dfgs
{
class dice
{
public static void Main(String[] args)
{
int plsc = 0;
int aisc = 0;
int turns = 0;
Random plrnd = new Random();
Random airnd = new Random();
while (turns < 11)
{
Console.WriteLine("Player Roll Is" + Convert.ToInt32(plrnd.Next(6)));
Console.WriteLine("AI Roll Is" + Convert.ToInt32(airnd.Next(6)));
plsc = plsc + plrnd;
aisc = aisc + airnd;
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
Console.ReadLine();
}
}
}
}
and whenever i try to compile i get the error Operator +' cannot be applied to operands of type int' and System.Random',this error appears twice,i tried changing the type of the random numbers to int but then i got the error messege Type int' does not contain a definition for Next' and no extension method Next' of type int' could be found. Are you missing an assembly reference? i am kinda stuck here,any help would be appreciated.
EDIT:Thank you to everyone who answered, i have managed to make this work,here is the final code,it's not the cleanest but works as intended:
namespace dfgs
{
class die
{
public static void Main(String[] args)
{
int plsc = 0;
int aisc = 0;
int turns = 0;
Random plrnd = new Random();
Random airnd = new Random();
while (turns < 10)
{
Console.WriteLine("Player Roll Is " + Convert.ToInt32(plrnd.Next(6)));
Console.WriteLine("AI Roll Is " + Convert.ToInt32(airnd.Next(6)));
plsc = plsc + plrnd.Next(6);
aisc = aisc + airnd.Next(6);
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
else{
break;
}
if (turns == 10){
if (plsc > aisc){
Console.WriteLine("The Player Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
}
else if (aisc > plsc){
Console.WriteLine("The AI Has Won,Ai Score: " + aisc + " Player Score: " + plsc);
}
break;
}
}
Console.ReadLine();
}
}
}
You probably want to save the random int you get from the Random, rather than trying to calculate number, plus a random_number_generator_machine - which, in some real world terms would be like asking someone "what is your age, divided by a cheese sandwich?"..
var plroll = plrnd.Next(6);
var airoll = airnd.Next(6);
Console.WriteLine("Player Roll Is" + plroll);
Console.WriteLine("AI Roll Is" + airoll));
plsc = plsc + plroll;
aisc = aisc + airoll;
You don't need a Random for the player and a Random for the computer; one Random could adequately generate for both, btw:
int plsc = 0;
int aisc = 0;
int turns = 0;
Random r = new Random();
while (turns < 11)
{
var plroll = r.Next(6);
var airoll = r.Next(6);
Console.WriteLine("Player Roll Is" + plroll);
Console.WriteLine("AI Roll Is" + airoll));
plsc = plsc + plroll;
aisc = aisc + airoll;
Look at this line:
plsc = plsc + plrnd;
In this code, plrnd is not a number. Instead, it's a generator for producing numbers. You must tell the generator to give you the next number, as you did on the line above:
plrnd.Next(6)
Moreover, you likely need to change the code above to save the results of each call in variables so you can use that same value to both show to the user and increment the total count.
Since you want to use the result of the roll multiple times, start by assigning the results to a variable for later use:
while (turns < 11)
{
// roll dies, store results in local variable
var plRoll = plrnd.Next(6);
var aiRoll = airnd.Next(6);
// then reuse the variables
Console.WriteLine("Player Roll Is " + plRoll);
Console.WriteLine("AI Roll Is " + aiRoll);
plsc = plsc + plRoll;
aisc = aisc + aiRoll;
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
else {
// remember to break out if the player doesn't want to continue
break;
}
}
int is a built in value data type in C#. Random is a class object. The + operator does not know how to add an int data type and a Random class object together. What you probably meant to do is to use the Next() method, which does return an int. Also, you only want to new up the Random class one time. Consider using this code instead:
namespace dfgs
{
class dice
{
public static void Main(String[] args)
{
Random rnd = new Random();
int plsc = 0;
int aisc = 0;
int turns = 0;
int plrnd = rnd.Next(6);
int airnd = rnd.Next(6);
while (turns < 11)
{
Console.WriteLine("Player Roll Is" + plrnd);
Console.WriteLine("AI Roll Is" + airnd);
plsc = plsc + plrnd;
aisc = aisc + airnd;
Console.WriteLine("Type A and hit enter to go again");
string nxt = Console.ReadLine();
if (nxt == "A"){
turns++;
}
Console.ReadLine();
}
}
}
}
I'm trying to return out of a method in C#, but every time I run the program I get a message that I'm creating a variable but never using it, then I get errors that the current variable does not exist in current context.
I am relatively new to C#, and I might be really dumb but if anyone can help me that will be great!
The code:
using System;
class MainClass
{
public static void Main()
{
int health = 3;
int powerCrystals = 0;
int healthCrystals = 0;
int basicEnemyDamage = 1;
int basicEnemyScore = 10;
string basicEnemyDrops = "1 powerCrystal";
int score = 0;
// Basic Enemies Drop 1 powerCrystal.
// Moderate Enemies Drop 1 powerCrystal and 1 healthCrystal.
// Advanced Enemies Drop 2 powerCrystals and 1 healthCrystal.
// Bosses Drop 3 powerCrystals and 3 healthCrystals.
Console.WriteLine("Input your username:");
string userName = Console.ReadLine();
Console.WriteLine("Welcome, " + userName);
Console.WriteLine("To check your stats, write: stats");
TrollFight();
}
static void TrollFight()
{
Console.WriteLine(userName + "! There is a pack of trolls aproaching! Guess the right number to kill them!");
Console.WriteLine("Your current health is = " + health);
Console.WriteLine("Guess the correct number and then you can defeat the trolls! It is between 1-9!");
int guessedNumber = Convert.ToInt32(Console.ReadLine());
if (guessedNumber == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again!");
health = health - basicEnemyDamage;
}
int guessedNumber2 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber2 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 2");
health = health - basicEnemyScore;
}
int guessedNumber3 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber3 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 1");
Console.WriteLine("You are almost dead! You do not have any Health Crystals so you can't heal!");
health = health - basicEnemyScore;
}
int guessedNumber4 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber4 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You died! Your final score = " + score);
health = health - basicEnemyDamage;
}
Console.WriteLine("To check your stats, write: stats");
}
}
I'm trying to return out of a method but it gives me a CS0219 warning
Ok a few things. The difference between a Void/Subroutine and a Function is that a Function returns something. Both your methods are voids, they don't return anything:
public static void Main()
static void TrollFight()
The problem with the variables is that they are out of scope.
Local - visible within the method
Private - visible to the class
Public - visible outside the assembly
One solution is to make the variables Private member variables:
class MainClass {
private int health = 3;
private int powerCrystals = 0;
private int healthCrystals = 0;
private int basicEnemyDamage = 1;
private int basicEnemyScore = 10;
private string basicEnemyDrops = "1 powerCrystal";
private int score = 0;
public static void Main() {
Run the project, this should fix it. The problem with using Private variable scope is it can get messy when multiple methods can change variables (without the other knowing). In this case we can use parameters to pass variables to voids or functions:
TrollFight(basicEnemyDamage);
...
static void TrollFight(string basicEnemyDamage) {
A good design will use all three with local variables:
class MainClass {
private int health = 3;
private string basicEnemyDrops = "1 powerCrystal";
private int score = 0;
public static void Main() {
...
}
static void TrollFight(string basicEnemyDamage) {
int powerCrystals = 0;
int healthCrystals = 0;
int basicEnemyDamage = 1;
int basicEnemyScore = 10;
I'd even change the void to return the Score:
static int TrollFight(string basicEnemyDamage, int score)
{
return score;
}
The Code:
using System;
public class MainClass {
private int health = 3;
private int score = 0;
private int powerCrystals = 0;
private int healthCrystals = 0;
private int basicEnemyDamage = 1;
private int basicEnemyScore = 10;
private string basicEnemyDrops = "1 powerCrystal";
public static void Main() {
//Basic Enemies Drop 1 powerCrystal.
//Moderate Enemies Drop 1 powerCrystal and 1 healthCrystal.
//Advanced Enemies Drop 2 powerCrystals and 1 healthCrystal.
//Bosses Drop 3 powerCrystals and 3 healthCrystals.
Console.WriteLine("Input your username:");
string userName = Console.ReadLine();
Console.WriteLine("Welcome, " + userName);
Console.WriteLine("To check your stats, write: stats");
TrollFight(userName);
}
static void TrollFight(string userName) {
Console.WriteLine(userName + "! There is a pack of trolls approaching! Guess the right number to kill them!");
Console.WriteLine("Your current health is = " + health.ToString());
Console.WriteLine("Guess the correct number and then you can defeat the trolls! It is between 1-9!");
int guessedNumber = Convert.ToInt32(Console.ReadLine());
if (guessedNumber == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again!");
health = health - basicEnemyDamage;
}
int guessedNumber2 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber2 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 2");
health = health - basicEnemyScore;
}
int guessedNumber3 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber3 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 1");
Console.WriteLine("You are almost dead! You do not have any Health Crystals so you can't heal!");
health = health - basicEnemyScore;
}
int guessedNumber4 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber4 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You died! Your final score = " + score.ToString());
health = health - basicEnemyDamage;
}
Console.WriteLine("To check your stats, write: stats");
}
}
I've just started studying the C#. And bumped into a problem:
When I use the Console.WriteLine in the Main method, it works just fine. However, when I try to break the code into methods, the WriteLine does not return anything. (I use Visual Studio to build and compile the project).
The task is to find a final amount of money a person would get when depositing money based on monthly capitalization. I kinda suspect I just messed up some trivial thing, but would still appreciate an explanation :) Thanks
The code without methods:
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
//Separating the input string into substrings
string[] separated = userInput.Split(' ');
//Getting the main variables
double sum1 = double.Parse(separated[0]);
double oneMonthPercentage = double.Parse(separated[1]) / 1200; //find a montly amount in percent = amount / 12 month / 100
double months = double.Parse(separated[2]);
double initialSum = sum1;
//Calculation of the final ammount
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
}
}
OUTPUTS - no_methods
The code with methods (WriteLine does not work):
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
}
//Separating string into substrings
public static string[] SeparateString(string userInput)
{
string[] separated = userInput.Split(' ');
return separated;
}
//calculating the final amount at the end of deposit time
public static double Calculate(string userInput)
{
// defining main variables for calculation
double sum1 = double.Parse(SeparateString(userInput)[0]);
double oneMonthPercentage = double.Parse(SeparateString(userInput)[1]) / 1200;
double months = double.Parse(SeparateString(userInput)[2]);
double initialSum = sum1;
//calculation as to the formula
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
return sum1;
}
}
OUTPUTS - with_methods
You need to call those methods to make them work. Right now you are only calling the initial WriteLine and ReadLine
You don't call any method. You should call Calculate() method:
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
var result = Calculate(userInput); // call here
}
I need help accessing an array's specific value within a separate method. During this program I am supposed to write a program that will ask the user to enter rainfall amounts for each month of a calendar year. The program will then determine total annual and average monthly rainfall amounts and finally will allow the user to search for a specific amount.
I am supposed to do this for the last method: SearchForAmounts() – this method will be a void method and have two double arrays for the parameter
list, one for the rainfall amount array and one for the array with the months. It will ask the user for a rainfall amount to search for in the array. It will then either report back in which month that amount first fell or it will
report that no rain of that amount fell that year. It will use one of the Array class methods to determine what to output. It will do this twice in the method – i.e. will repeat the code twice in the method.
I am having troubles finding a way to access the value in the monthInTheYear array. Here is my code:
namespace CJohnson_Prog8
{
class Program
{
static void Main(string[] args)
{
string[] monthInTheYear;
double[] rainfallAmmounts;
monthInTheYear = new string[12] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
rainfallAmmounts = new double[12];
Console.WriteLine("Welcome to the Annual Rainfall Program");
GetRainFall(rainfallAmmounts, monthInTheYear);
PrintAmounts(rainfallAmmounts, monthInTheYear);
TotalYearRain(rainfallAmmounts);
SearchForAmounts(rainfallAmmounts, monthInTheYear);
}
public static void GetRainFall(double[] rainfall, string[] month)
{
for (int i = 0; i < rainfall.Length; i++)
{
Console.Write("Enter the rainfall in inches in {0}: ", month[i]);
rainfall[i] = double.Parse(Console.ReadLine());
while (rainfall[i] < 0)
{
Console.Write("Enter the rainfall in inches in {0}: ", month[i]);
rainfall[i] = double.Parse(Console.ReadLine());
}
}
}
public static void PrintAmounts(double[] rainfall, string[] month)
{
for (int i = 0; i < rainfall.Length; i++)
{
Console.WriteLine("{0}\t\t{1:F2}", month[i], rainfall[i]);
}
}
public static double TotalYearRain(double[] totalrainFall)
{
double averageRainFall;
double sum = 0;
for (int i = 0; i < totalrainFall.Length; i++)
{
sum += totalrainFall[i];
}
averageRainFall = sum / 12;
Console.WriteLine("");
Console.WriteLine("Total Annual Rain is: {0:F2}", sum);
Console.WriteLine("Average Month Rain: {0:F2}", averageRainFall);
return sum;
}
public static void SearchForAmounts(double[] searchRainFall, string[] searchMonths)
{
Console.Write("Enter a rainfall amount to search for: ");
double RainFall = double.Parse(Console.ReadLine());
if (Array.IndexOf(searchRainFall, RainFall) != 1)
{
Console.WriteLine(searchMonths[i] + " was the first month to have " + RainFall + " inches fell this year.");
}
else
{
Console.WriteLine("No rainfall of " + RainFall + " inches fell that year.");
}
}
}
}
for (int i = 0; i <= 1; i++) {
//do stuff
var index = Array.IndexOf(searchRainFall, RainFall);
if (index > -1) {
Console.WriteLine(searchMonths[index] + " was the first month to have " + RainFall + " inches fell this year.");
} else {
Console.WriteLine("No rainfall of " + RainFall + " inches fell that year.");
}
}
here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.