C# problems with a for loop - c#

Can someone tell me why this doesnt work. When I enter the loop it prints everything instead of one line and get the users input. It prints Enter the integer the account numberEnter the integer the account balanceEnter the account holder lastname
Got it working thanks everyone, but now the searchaccounts doesnt work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class accounts
{
private int[] accountnum = new int[5]; //private accountnum array of five integer account numbers
private int[] accountbal = new int[5];//private balance array of five balance amounts
private string[] accountname = new string[5];//private accntname array to hold five last names
public void fillAccounts()
{
int bal;
int accountnumber;
string name;
for (int x = 0; x < 5; ++x)
{
Console.Write("Enter the integer the account number");
accountnumber = Console.Read();
Console.Write("Enter the integer the account balance");
bal = Console.Read();
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
accountnum[x] = accountnumber;
accountbal[x] = bal;
accountname[x] = name;
}
}
public void searchAccounts()
{
Console.WriteLine("Enter the account number");
int acctnum = Console.Read();
for (int x = 0; x < 6; ++x)
{
if (x < 5)
{
if (accountnum[x] == acctnum)
{
Console.WriteLine("Account #{0} has a balance of {1} for customer {2}", acctnum, accountbal[x].ToString("C"), accountname[x]);
break;
}
}
else
{
Console.WriteLine("You entered invalid account number");
}
}
}
public void averageAccounts()
{
int sum = 0;
int avg;
for (int x = 0; x < 5; ++x)
{
sum = accountbal[x] + sum;
}
avg = sum / 5;
Console.WriteLine("The average dollar amount is {0}", avg.ToString("c"));
}
}
class assignment3_alt
{
static void Main(string[] args)
{
accounts myclass = new accounts();
string userin;
myclass.fillAccounts();
int i = 0;
while (i != 1)
{//use the following menu:
Console.WriteLine("*****************************************");
Console.WriteLine("enter an a or A to search account numbers");
Console.WriteLine("enter a b or B to average the accounts");
Console.WriteLine("enter an x or X to exit program");
Console.WriteLine("*****************************************");
Console.Write("Enter option-->");
userin = Console.ReadLine();
if (userin == "a" || userin == "A")
{
myclass.searchAccounts();
}
else if (userin == "b" || userin == "B")
{
myclass.averageAccounts();
}
else if (userin == "x" || userin == "X")
{
break;
}
else
{
Console.WriteLine("You entered an invalid option");
}
}
}
}
}

Console.Read only reads a single character. You need to use Console.ReadLine.
Console.Write("Enter the integer the account number");
accountnumber = int.Parse(Console.ReadLine());
Console.Write("Enter the integer the account balance");
bal = int.Parse(Console.ReadLine());
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
You might also want to consider using int.TryParse instead of int.Parse so that you can better handle invalid input.

For your new question it is the same error. Just replace:
int acctnum = Console.Read();
with
int acctnum = int.Parse(Console.ReadLine());
or (preferably)
int acctnum;
if (!int.TryParse(Console.ReadLine(), out acctnum))
{
Console.WriteLine("You need to enter a number");
return;
}
The first will fail if the user doesn't enter a valid integer the second will print out a nice error message and return to the loop.

This is not an answer, as other have already put up some good ones. These are just a few tips about your code.
Instead of looping with while (i != 1), never changing the value of i and terminating the loop with break, it would be better to use a do-while loop, like this:
do
{
// blah blah
} while(userin != "x" || userin != "X")
It is less confusing than having a variable with no use at all.

Related

I want to write a program that calculates the sum and average of student grades

Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}

Noob needing help on breaking out of loop

I'm very sorry this is such an easy question, I'm just starting out. I've created code that allows a user to enter a number of random dice rolls, and outputs the sum of those rolls. I've now been asked to create a loop that repeats these steps, including the prompt, until the user types 'quit'. My issue is that my code converts the string to an integer, so typing anything kills the code. Any tips of how to insert the loop and break? My code is:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
int numberDice = Convert.ToInt32(numberDiceString);
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.ReadKey();
}
I wouldn't use a "while(true)" statement. As someone pointed out in the comments i would prefer using the right condition in there.
That being said i would do it this way:
static void Main(string[] args)
{
Random random = new Random();
string numberDiceString;
int numberDice;
Console.WriteLine("Enter a number of dice to roll:");
while ((numberDiceString = Console.ReadLine()) != "quit")
{
bool parsed = int.TryParse(numberDiceString, out numberDice);
if (!parsed)
{
//Handle the error. The user input was not a number or "quit" word
break;
}
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.WriteLine("Enter a number of dice to roll:");
}
}
I have to say that i prefer this way because you can easily see when the loop will stop. Also i added an error handling that you should be doing (What happen if the user enters any words that are not numbers?).
Hope this helps.
This change should be fairly simple. What you need to do is to create a while loop, and then a check before you actually parse for an int. The psuedocode for this would be something like.
while(true) {
//Ask for input
//Check if it equals "quit"
//If so -> break;
//If not convert to int
//For Loop for dice rolls
//Print Total
}
I'm sure it could be a little more elegant than this, and you would want to put some more checks to make sure that invalid input doesn't crash the program, but it should get the job done.
This is a very simple solution that shows how to parse the user input.
using System;
namespace Simpleton
{
class Program
{
static public int GetChoice()
{
int choice = 0;
while (true)
{
Console.Write("Enter number of rolls or \"quit\" to finish: ");
var answer = Console.ReadLine();
if (String.Compare(answer, "quit", true) == 0)
{
return 0; // Done
}
if (Int32.TryParse(answer, out choice))
{
return choice;
}
}
}
static void Main(string[] args)
{
var choice = 0;
while ((choice = GetChoice()) > 0)
{
Console.WriteLine($"You'll be looping {choice} times.");
for (int tries = 0; tries < choice; tries++)
{
// Looping
}
}
}
}
}
Try this code:
static void Main(string[] args)
{
Random random = new Random();
while(true)
{
String numberDiceString = "";
int numberDice = 0;
Console.WriteLine("Enter a number of dice to roll:");
numberDiceString = Console.ReadLine();
if (numberDiceString == "quit") { return; }
int total = 0;
if (Int32.TryParse(numberDiceString, out numberDice))
{
total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
}
Console.WriteLine(total);
}
}
I'm not a C# programmer, but you can test for "quit" explicitly and use a goto
BeginLoop:
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
if (numberDiceString == "quit")
{
goto EndLoop;
}
int numberDice = Convert.ToInt32(numberDiceString);
/* Rest of code you want to do per iteration */
goto BeginLoop;
EndLoop:

How to display highest and lowest of an array

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.

C# console application - commission calculator - how to use method within method

I'm new to C# and I have encountered some problems with my console application that I'm recently working on. I am trying to have 3 methods:
getsales to get the sales the user made, calcCom to calculate the commission for the sales and finally main to make them work and establish the program.
I'm having trouble to make those methods work with(in) each other.
After i entered all the sales, the program goes to the else-statement and tells me "invalid entry". Since i haven't really gotten to output the variables I didn't expect any kind of output, but I want the program to tell the user the commission and sale for each person.
Please excuse me if I misused any terms or words, like I said I am new to this language! :D
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication38
{
class Program
{
public static void getsales ()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
Console.WriteLine();
}
}
public static void calcComm ()
{
double total = 0;
double comm = 0;
comm = total * 0.2;
}
static void Main()
{
Console.WriteLine(" Sunshine Hot Tubs \n Sales Commissions Report\n");
char Letter;
string name;
const string name1 = "Andreas";
const string name2 = "Brittany";
const string name3 = "Eric";
string inputLetter;
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
while (Letter != 'z')
{
if (Letter == 'a')
{
name = name1;
getsales();
calcComm();
}
if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
}
}
}
}
I think your problem is you need this:
if (Letter == 'a')
{
name = name1;
getsales();
calcComm();
}
else if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
else if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
You also need to copy this code after the else block, at the very end of your while loop.
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
Also, remove this line from inside the else block. It isn't needed.
inputLetter = Console.ReadLine();
You probably intended to display the commision on the console. Change your getsales and calcComm to look like this:
public static void getsales ()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
Console.WriteLine();
}
calcComm(total);
}
public static void calcComm (double total)
{
double comm = 0;
comm = total * 0.2;
Console.WriteLine(comm);
}
Then remove all calls to calcComm from the Main method.
The variable "total" is in the two methods and they do not persist the data that you are looking for between the two methods that you have defined. That is, the total variable in getSales() method is different from calcComm() method.
You should move this:
double total = 0;
outside of the two methods and put it within the class with a static scope. Like:
class Program
{
static double total;
Also, reinitialize total to zero within your getSales() method.
calcComm() doesn't do anything...
I think you might want to have some of your variables as global so that if they are modified by a method you can still retrieve their value, or even better pass them to the method and get them returned with the new values.
To declare global variables you should declare them inside the class Program but outside any method and then make sure that no other methods have variables with the same name

How do I prevent crashing due to invalid input in C#?

The program I've written is set to only accept positive integers as input. If the user inputs a letter instead, then it crashes. Negative integers don't cause any problems, though it's not 'valid' in regards to how my program functions.
What I want to do is:
Prevent the program from crashing from invalid input.
Display an error message if the input is invalid
Have the program continue where it left off, without affecting the rest of the program.
Also, a part of my program involves division. Is there a way to prevent the user from entering all zeros?
This is in C#
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue;
do
{
Console.WriteLine("Enter Striking Level: ");
string striking = Console.ReadLine();
Console.WriteLine("Enter Grappling Level: ");
string grappling = Console.ReadLine();
Console.WriteLine("Enter Submission Level: ");
string submission = Console.ReadLine();
Console.WriteLine("Enter Durability Level: ");
string durability = Console.ReadLine();
Console.WriteLine("Enter Technical Level: ");
string technical = Console.ReadLine();
Console.WriteLine("Enter Speed Level: ");
string speed = Console.ReadLine();
Console.WriteLine("Enter Hardcore Level: ");
string hardcore = Console.ReadLine();
Console.WriteLine("Enter Charisma Level: ");
string charisma = Console.ReadLine();
int gra = Convert.ToInt32(grappling);
int str = Convert.ToInt32(striking);
int dur = Convert.ToInt32(durability);
int spd = Convert.ToInt32(speed);
int tec = Convert.ToInt32(technical);
int hdc = Convert.ToInt32(hardcore);
int cha = Convert.ToInt32(charisma);
int sub = Convert.ToInt32(submission);
int total = str + gra + sub + dur + tec + spd + cha + hdc;
int overall = total / 8 + 8;
Console.WriteLine("The Overall is " + overall);
Console.WriteLine("Do you wish to continue? y/n? ");
if (Console.ReadLine() == "y")
{
shouldContinue = true;
}
else break;
} while (shouldContinue == true);
}
}
}
int value = 0;
if (!int.TryParse(input, out value))
{
MessageBox.Show("Oops");
} else {
// use the value in the variable "value".
}
static void Main(string[] args)
{
bool validInput = false;
string inputString;
UInt32 validPositiveInteger = 0;
while (!validInput)
{
Console.WriteLine("Please enter a positive 32 bit integer:");
inputString = Console.ReadLine();
if (!UInt32.TryParse(inputString, out validPositiveInteger))
{
Console.WriteLine("Input was not a positive integer.");
}
else if (validPositiveInteger.Equals(0))
{
Console.WriteLine("You cannot enter zero.");
}
else
{
validInput = true;
//Or you could just break
//break;
}
}
Console.WriteLine(String.Format("Positive integer = {0}", validPositiveInteger));
}
Here you go:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue = true;
while (shouldContinue)
{
int strikingLevel = GetValue("Enter Striking Level: ");
int grapplingLevel = GetValue("Enter Grappling Level: ");
int submissionLevel = GetValue("Enter Submission Level: ");
int durabilityLevel = GetValue("Enter Durability Level: ");
int technicalLevel = GetValue("Enter Technical Level: ");
int speedLevel = GetValue("Enter Speed Level: ");
int hardcoreLevel = GetValue("Enter Hardcore Level: ");
int charismaLevel = GetValue("Enter Charisma Level: ");
int total = strikingLevel + grapplingLevel + durabilityLevel + submissionLevel +
technicalLevel + speedLevel + charismaLevel + hardcoreLevel;
int overall = total / 8 + 8;
Console.WriteLine("\nThe Overall is {0}.", overall);
while (true)
{
Console.WriteLine("Do you wish to continue? y/n? ");
string response = Console.ReadLine();
if (response.Equals("y", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = true;
break;
}
else if (response.Equals("n", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = false;
break;
}
}
}
}
private static int GetValue(string prompt)
{
while (true)
{
Console.WriteLine(prompt);
string input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if (value <= 0)
Console.WriteLine("Please enter a positive number.");
else
return value;
}
else
{
Console.WriteLine("Please enter a number.");
}
}
}
}
}
Yes... before you do anything calculations, you need to validate the data you are going to use. If any data is incorrect, then you display a messagebox detailing the errors and return focus to the form so the user can fix the errors. Repeat as necessary.
I wrote this one many moons ago when I first learned C#. It is a conversion from a VB function that I got back in VB5 days. The major benefit of the function is that there is no error - an input will just not allow any characters outside of the predefined list.
/***********************************************************************
* bool ValiText(char inChar,
* string valid,
* bool editable,
* bool casesensitive
* Description: Validate Input Characters As They Are Input
* Notes: For each control whose input you wish to validate, just put
* e.Handled = ValiText(e.KeyChar, "0123456789/-" [,true][,true])
* In The KeyPress Event
***********************************************************************/
public bool ValiText(char inChar, string valid, bool editable, bool casesensitive)
{
string inVal = inChar.ToString();
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
/// Case InSensitive - Make Them Both The Same Case
if (!casesensitive)
{
tst = tst.ToLower();
inVal = inVal.ToLower();
}
return tst.IndexOf(inVal,0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid, bool editable)
{
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
return tst.IndexOf(inChar.ToString(),0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid)
{
return valid.IndexOf(inChar.ToString(),0,valid.Length) < 0;
}
Note That This Will Not Work On A Web APP.

Categories