Not receiving the correct Output in C# - c#

So I am doing a homework assignment and for some reason my variable is not giving me the correct output. Using 6, 7, 8, 9, 10 as the judge scores and 1.2 as the degree of difficulty, I should receive 9.6 back for the final dive score.. but for some reason I am receiving 8.. Any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rickerson_Bret_iLab3
{
class Program
{
static void Main(string[] args)
{
string wouldContinue;
do
{
string diverName;
string diverCity;
double degreeofDiff = 0;
double scoreJudge = 0;
bool validDegree = false;
double totalJudgeScore = 0;
int i = 1;
double highJudgeScore = 0;
double lowJudgeScore = 0;
Console.WriteLine("Enter the diver's name...");
diverName = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter the diver's city...");
diverCity = Convert.ToString(Console.ReadLine());
while (validDegree == false)
{
Console.WriteLine("Enter the degree of difficulty for this dive...");
degreeofDiff = Convert.ToDouble(Console.ReadLine());
if (degreeofDiff < 1.00 || degreeofDiff > 1.67)
{
Console.WriteLine("Re-enter a valid degree of difficulty (Valid Range: 1.00 - 1.67");
validDegree = false;
}
else
{
validDegree = true;
}
}
while (i < 6)
{
Console.WriteLine("Enter the judge #" + i + " score...");
scoreJudge = Convert.ToDouble(Console.ReadLine());
if (scoreJudge > 10 || scoreJudge < 1)
{
bool validScore = false;
while (validScore == false)
{
Console.WriteLine("Enter a valid Judge Score for judge #" + i + "...");
scoreJudge = Convert.ToDouble(Console.ReadLine());
if (scoreJudge > 10 || scoreJudge < 1)
{
validScore = false;
}
else
{
validScore = true;
}
}
}
if (scoreJudge > highJudgeScore)
{
highJudgeScore = scoreJudge;
Console.WriteLine(highJudgeScore);
}
if (scoreJudge < lowJudgeScore)
{
lowJudgeScore = scoreJudge;
Console.WriteLine(lowJudgeScore);
}
i++;
totalJudgeScore = totalJudgeScore + scoreJudge;
Console.WriteLine(totalJudgeScore);
Console.WriteLine(scoreJudge);
}
double highLow = highJudgeScore + lowJudgeScore;
totalJudgeScore = totalJudgeScore - highLow;
totalJudgeScore = (totalJudgeScore / 3) * degreeofDiff;
Console.WriteLine("Diver: " + diverName);
Console.WriteLine("Diver City: " + diverCity);
Console.WriteLine("Dive Degree of Difficulty: " + degreeofDiff);
Console.WriteLine("Dive Score: " + totalJudgeScore);
Console.WriteLine("Would you like to enter another diver? Enter y for yes or n for no...");
wouldContinue = Convert.ToString(Console.ReadLine());
wouldContinue.ToUpper();
} while (wouldContinue == "Y");
}
}
}
I want to add. I attempted to verify that it was accepting the data correctly by having it display the variables as it went through or anytime the variable was manipulated...it appears to be correct throughout but at the end is when I have the issue with variable "totalJudgeScore"
Edit2: I have since found that for some reason the code is not following the last 2 if statements properly. It is storing "scoreJudge" to "highJudgeScore" and "lowJudgeScore" each time and overwriting the data incorrectly.

Your lowJudgeScore is never getting set after it gets set to 0. You should have it default to 10 or higher, so that it gets set correctly.
Try this:
double lowJudgeScore = 10.0;

What happens is that the lowJudgeScore is never set during the loop. Add this else block and to initialize the lowJudgeScore...
if (scoreJudge < lowJudgeScore)
{
lowJudgeScore = scoreJudge;
Console.WriteLine(lowJudgeScore);
}
//Add this else block to initialize the low score variable
else if (lowJudgeScore == 0)
{
lowJudgeScore = scoreJudge;
}

Related

C# How can I Validate a User input before it is placed into my array?

I am very new to C# and I was wondering how I can validate user input before placing their input in my array. I am trying to create a console application to create a vertical and horizontal histogram, made of stars. So I am asking the user for 8 numbers between 1-10 and printing their results onto the screen as a histogram.
I need help with 3 things:
1. How can I make it so that they can only enter numbers into the menu and the array?
2. I'm not sure how to display the histogram vertically, I've done the horizontal one and can't figure out how to make it vertical.
3. Also, I'd like to have labels going down the histograms. E.g
1 **** (Number of stars user selected)
2 ****** (Number of stars user selected)
3 ***** (Number of stars user selected)
4 * etc.
Would greatly appreciate any help! Thank you so much in advance. :)
Here is what I've got so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class Program
{
static void Main(string[] args)
{
clsMainMenu MainMenu = new clsMainMenu();
ConsoleKeyInfo ConsoleKeyPressed;
do
{
MainMenu.DisplayMenu();
ConsoleKeyPressed = Console.ReadKey(false);
Console.WriteLine();
switch (ConsoleKeyPressed.KeyChar.ToString())
{
case "1":
clsHistogram Histogram = new clsHistogram();
Histogram.CreateHorizontalHistogram();
break;
case "2":
clsHistogram HistogramV = new clsHistogram();
HistogramV.CreateVerticalHistogram();
break;
}
} while (ConsoleKeyPressed.Key != ConsoleKey.Escape);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsMainMenu
{
public void DisplayMenu()
{
Console.WriteLine("1. Create a Horizontal Histogram.");
Console.WriteLine("2. Create a Vertical Histogram.");
Console.WriteLine("Press Esc to exit the Program.");
Console.WriteLine("..................................");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsHistogram
{
string strNumberChosen = "";
public void CreateHorizontalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" *");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Horizontal Array.
}
public void CreateVerticalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" * \n");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Vertical Array.
}
}
}
Here is an example of code that would use the int.TryParse() method to evaluate the entered data.
private static readonly char star = '*';
private static readonly uint minValue = 1;
private static readonly int maxValue = 10;
private static void CreateHorizontalHistogram()
{
var limits = "a number between " + minValue + " and " + maxValue + ": ";
Console.WriteLine("Please enter " + limits);
var list = new List<int>();
do
{
var message = string.Empty;
bool isNumber = false;
bool isRightSize = false;
int output;
do
{
var input = Console.ReadLine();
isNumber = int.TryParse(input, out output);
if(isNumber)
{
isRightSize = minValue <= output && output <= maxValue;
message = isRightSize ? "That will do: " : "Try again - value is not " + limits + output;
}
else
{
message = "Try again - " + input + " is not a Number";
}
Console.WriteLine(message);
}while(!isNumber || !isRightSize);
Console.WriteLine("Entered number at position" + (list.Count + 1) + " : " + output);
list.Add(output);
}while(list.Count <= 8);
Console.WriteLine("Your Histogram looks like this: ");
foreach(var value in list)
{
Console.WriteLine(string.Empty.PadRight(value, star));
}
Console.WriteLine("Or like this with LINQ");
list.ForEach(n => Console.WriteLine(string.Empty.PadRight(n, star)));
}
NOTE:
I used a List<int> of integers instead of an array int[]...my personal preference.
I changed the way the diagram was created. My version is a bit less verbose.
I also added an additional example of how you could create the diagram using LINQ-- always looks good.
Please, let me know if you have any questions.

Question about executing a while loop in C#

So I have this code where you enter your "area code" and then you enter how long you would like the call to be. This is basically a simple calculator that would find the cost of how much a call would be depending on your area code. I am having trouble trying to figure out how to keep the loop running if I enter in an invalid area code. As of now if I enter in an invalid area code the entire program will just end in the command prompt. Heres the code:
using System;
using static System.Console;
namespace Chapter6._1
{
class Program
{
static void Main()
{
// array info //
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int x;
int areaCode;
double cost = 0;
int callLength;
bool validAreacode = false;
// start of actual code //
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
if (validAreacode)
{
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * cost;
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
}
}
You might wrap your Read and Check routine into another while-loop:
bool validAreacode = false;
while(!validAreacode)
{
// start of actual code //
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
This is the simplest solution for you (not so much changes in your code required). But your code still has the problems. Your program will be crashed if user tries to print any not digit character instead of area code.
You can do a do-While here:
Basically when you do do-while you force the code on the do to be done until the condition in the while is completed. in your case, you need to add the checking of the pohne number inside the do statement, and to know if the person selected a correct value, you can do Array.FindIndex():
this will be your do-while loop, also i chaned your x for index try to use names for the variables that have some meaning. (index is not perfect anyway)
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
and this will be your entire main method:
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int index;
int areaCode;
int callLength;
bool validAreacode = false;
// start of actual code //
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * phoneCost[index];
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
As you can see you can also remove the while you have to loop the array and the if-else for the valid codes. assuming that when the code reach that point, the area is correct.
It's a good practice to try to remove the number of if-else.
You probably need to loop the entire code section, something like this
while (true)
{
Write("Enter in the area code you want to call: ");
var input = ReadLine();
if (input == "Exit")
break;
areaCode = Convert.ToInt32(input);
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
else if (validAreacode)
{
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * cost;
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
Don't forget to add a check for when user types something that's not a digit

Keeping track of points in simple console game

I'm having a hard time wrapping my mind around this. Every time the player makes a wrong guess, it should subtract his/her bet from the initial balance.
Since it is in a loop, it always takes the initial balance from the beginning spits out the same balance every time. (obviously)
I've tried assigning different variables and just can't seem to figure it out.
I've omitted the medium and hard difficulty methods as they are of no use right now, until I figure out this one.
My Main() only calls the setDifficulty(). Nothing else.
class Control
{
int selectedNumber = 0;
Random num = new Random();
bool playAgain = true;
int difficulty = 0;
int bet = 0;
int initialBalance = 20;
int runningCredits = 0;
int credits = 0;
public Control()
{ }
//sets game difficulty
public void SetDifficulty()
{
Console.Clear();
Console.WriteLine("Please select level of difficulty between 1 - 100");
difficulty = int.Parse(Console.ReadLine());
if (difficulty >= 1 && difficulty <= 20)
LetsPlayEasy();
else if (difficulty >= 21 && difficulty <= 50)
LetsPlayMedium();
else if (difficulty >= 51 && difficulty <= 100)
LetsPlayHard();
else
{
SetDifficulty();
}
}
//easy level method
public void LetsPlayEasy()
{
//variables
int userGuess;
int numGuesses = 0;
selectedNumber = num.Next(1, 101);
Console.BackgroundColor = ConsoleColor.DarkYellow;
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Difficulty level = EASY");
Console.WriteLine("\nBeggining credit balance = " + initialBalance);
Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
bet = int.Parse(Console.ReadLine());
do
{
Console.WriteLine("\nGuess a number between 1 and 100.");
userGuess = Convert.ToInt32(Console.ReadLine());
numGuesses++;
UI output = new UI();
output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);
runningCredits = (initialBalance - bet);
Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");
} while (playAgain == true);
}
class UI
{
Random num = new Random();
int keepGoing;
public UI()
{ }
//compare user's guess to selected number
public void CompareNumbers(int userGuess, ref int selectedNumber, ref bool playAgain, ref int numGuesses)
{
Control difficulty = new Control();
Admin say = new Admin();
if (userGuess > selectedNumber)
{
Console.Beep(600, 300);
Console.WriteLine("\nToo High! Guess Again!");
}
else if (userGuess < selectedNumber)
{
Console.Beep(300, 300);
Console.WriteLine("\nToo Low! Guess Again!");
}
else
{
Console.Beep(350, 300);
Console.Beep(380, 200);
Console.Beep(380, 100);
Console.Beep(500, 1100);
Console.WriteLine("\n\nCongrats! It took you " + numGuesses + " guesses to win.");
numGuesses = 0;
Console.WriteLine("Press 1 to play again or 2 to quit.");
keepGoing = int.Parse(Console.ReadLine());
while (keepGoing != 1 && keepGoing != 2)
{
Console.WriteLine("\n\nPlease type either 1 or 2 only!");
keepGoing = int.Parse(Console.ReadLine());
}
if (keepGoing == 2)
{
playAgain = false;
say.Goodbye();
}
else
{
Console.Clear();
difficulty.SetDifficulty();
}
}
}
}
}
Initialise runningBalance to initialBalance and only use this value for calculations. If you only need initialBalance once, you can also do it by simply switching runningBalance to initialBalance without initializing runningBalance.
Console.WriteLine("\nBeggining credit balance = " + initialBalance);
Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
bet = int.Parse(Console.ReadLine());
runningBalance = initialBalance
do
{
Console.WriteLine("\nGuess a number between 1 and 100.");
userGuess = Convert.ToInt32(Console.ReadLine());
numGuesses++;
UI output = new UI();
output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);
runningCredits -= bet;
Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");
} while (playAgain == true);
runningCredits = (initialBalance - bet);
You don't change initialBalance or bet in the loop, so every iteration has the same value of runningCredits.
Outside the loop, do this:
runningCredits = initialBalance;
Inside the loop, do this:
runningCredits -= bet;
Note: you don't have any code to check in the loop to see if the user guessed right or wrong (and as such, the user always loses and you always subtract out the bet).

ReadLine(); between values

I made a dice game and just a few moments ago asked for a solution here, which i got. it made a new problem and in which i cant seem to find a answer.
Heres the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Noppapeli
{
class Program
{
static void Main(string[] args)
{
int pyöräytys;
int satunnainen;
int luku = 0;
Random noppa = new Random((int)DateTime.Now.Ticks);
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
Console.WriteLine("Haettava numero on: " + pyöräytys);
Console.ReadLine();
do
{
luku++;
satunnainen = noppa.Next(1, 7);
Console.WriteLine("numero on: " + satunnainen);
if (satunnainen == pyöräytys)
{
satunnainen = pyöräytys;
}
} while (pyöräytys != satunnainen);
Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
Console.WriteLine("Haettu numero: " + pyöräytys);
Console.WriteLine("Pyöräytetty numero: " + satunnainen);
Console.Write("Kesti " + luku + " Nopan pyöräytystä saada tulos!");
Console.ReadLine();
}
}
}
The problem is that int.TryParse(Console.ReadLine(),out pyöräytys); needs to only take values between 1-6. now if I put a 7 in there the game is on a loop to find a 7 from a D6.
Is there a easy solution or should i just make the dices bigger.
You simply need to add some kind of loop to ensure the value is valid and continue looping until a valid value is provided.
pyöräytys = -1; // Set to invalid to trigger loop
while (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
if (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Invalid value, must be 1-6"); // Error message
}
}
Just verify the input value is between 1 and 6:
bool valid;
while (!valid)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
valid = (pyöräytys > 0 && pyöräytys <= 6);
}

Check the length of integer variable

Is there a way to check a lenth of integer variable, and if is to long just trim it.
I hava a field in database that accepts 3 character, lenth is 3.
So is it possible to do like it's done with string variable
example:
cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref;
Thanks!
The easiest answer would be:
//The length would be 3 chars.
public int myint = 111;
myint.ToString().Length;
The following worked a treat for me!
public static int IntLength(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i == 0)
return 1;
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Original Source: http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm
You don't have to convert it to a string to make it shorter, that can be done numerically:
if (num > 999) {
num %= 1000;
}
This will cut of digits from the left, if you want to cut them off from the right:
while (num > 999) {
num /= 10;
}
If the value can be negative, also check:
if (num < -99) {
num = -(-num % 100);
}
or:
while (num < -99) {
num = -(-num / 10);
}
cust_ref = cust_ref.ToString().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
or simply use
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
Use like this
cust_ref= cust_ref.Tostring().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
Nont very clear what you're asking for, but as much as I unerstood you're asking for:
int a = 1234567890;
for some reason you want to make it shorter, like
int b = MakeShorter(a);
//b == 1234 (say)
If so, the easiest solution may be, convert it to string, made what you already implemented and reconvert it back to int.
If this is not what you're asking for, please clarify.
The conversion to the string is ugly way to implement it.
It's require a pure math solution
int CutTheNumber(int number, int maxLen)
{
var maxSize = (int)Math.Pow(10, maxlen);
if(maxSize <= Math.Abs(number))
{
number %= maxSize;
}
return number;
}
Checking length
length = cust_ref.ToString().Length;
Remove extra bits
if (length > need)
{
cust_ref =Convert.ToInt32( cust_ref.ToString().Remove(length -(length- need)));
}
for this u will have to do some simple stuffs.
like
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
or u can manually store it in any variable and the
You can try this code. use if else statement to check the validation ..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace avaragescore
{
class Program
{
static void Main(string[] args)
{
float quiz;
float midterm;
float final;
float avrg=0;
Start:
Console.WriteLine("Please enter the Quize Score here");
quiz = float.Parse(Console.ReadLine());
if(quiz > 100)
{
Console.WriteLine("You have entered wrong score please re-enter");
goto Start;
}
Start1:
Console.WriteLine("Please enter the Midterm Score here");
midterm = float.Parse(Console.ReadLine());
if(midterm > 100)
{
Console.WriteLine("You have entered wrong score please re- enter");
goto Start1;
}
Start3:
Console.WriteLine("Please enter the Final Score here");
final = float.Parse(Console.ReadLine());
if(final > 100)
{
Console.WriteLine("You have entered wrong Score Please re-enter");
goto Start3;
}
avrg = (quiz + midterm + final) / 3;
if(avrg >= 90)
{
Console.WriteLine("Your Score is {0} , You got A grade",avrg);
}
else if (avrg >= 70 && avrg < 90)
{
Console.WriteLine("Your Score is {0} , You got B grade", avrg);
}
else if (avrg >= 50 && avrg < 70)
{
Console.WriteLine("Your Score is {0} , You got C grade", avrg);
}
else if (avrg < 50)
{
Console.WriteLine("Yor Score is {0} , You are fail", avrg);
}
else
{
Console.WriteLine("You enter invalid Score");
}
Console.ReadLine();
}
}
}

Categories