This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I'm working on a program for my C# class that is supposed to take an entered amount, as a double or not, and to find change in dollars, quarters, etc.,
I'm using the Greedy Algorithm, and I keep getting some sort of error that reads, "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in 2D.exe".
I'm still relatively new to C#, and come from a Java and C++ Background.
So far I have my Money class:
using System;
using static System.Console;
namespace _2D
{
class Money
{
private double dollars, cents;
public void IncrementMoney() { }
public void DecrementMoney() { }
public Money(double dollarsncents)
{
double amountLeftOfDecimal = Math.Truncate(dollarsncents);
double amountRightOfDecimal = Math.Floor(dollarsncents);
this.dollars = Math.Round(amountLeftOfDecimal);
//the following LOGIC needs to be wokred out:
this.cents = Math.Round((amountRightOfDecimal * 100) / 100, 2);
}
public Money(int ddollars, int ccents)
{
this.dollars = ddollars;
this.cents = ccents;
}
public override string ToString()
{
return String.Format(dollars + " dollars and " + cents + " cents.");
}
public void CoinAmounts(int inAmount, int remainder, int[] coins)
{
if((inAmount % 0.25) < inAmount)
{
coins[3] = (int)(inAmount / 0.25);
remainder = inAmount % (1/4);
inAmount = remainder;
}
if ((inAmount % 0.1) < inAmount)
{
coins[2] = (int)(inAmount / 0.1);
remainder = inAmount % (1/10);
inAmount = remainder;
}
if ((inAmount % 0.05) < inAmount)
{
coins[1] = (int)(inAmount / 0.05);
remainder = inAmount % (1/20);
inAmount = remainder;
}
if ((inAmount % 0.01) < inAmount)
{
coins[0] = (int)(inAmount / 0.01);
remainder = inAmount % (1/100);
}
}
public void PrintChange(int[] arr)
{
if (arr[3] > 0)
Console.WriteLine("Number of quarters: " + arr[3]);
if (arr[2] > 0)
Console.WriteLine("Number of dimes: " + arr[2]);
if (arr[1] > 0)
Console.WriteLine("Number of nickels: " + arr[1]);
if (arr[0] > 0)
Console.WriteLine("Number of pennies: " + arr[0]);
}
}
And my Main :
using System;
namespace _2D
{
class Program
{
static void Main(string[] args)
{
Money MyMoney = new Money(23, 24);
Console.WriteLine(MyMoney.ToString());
Money dollarCentAmount = new Money(12.45);
Console.WriteLine(dollarCentAmount.ToString());
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Enter an amount you'd like change for: ");
double inAmountDouble = Convert.ToDouble(Console.ReadLine());
int inAmount = Convert.ToInt32(inAmountDouble);
int tochange = inAmount;
int remainder = 0;
int[] coins = new int[3];
MyMoney.CoinAmounts(inAmount, remainder, coins);
Console.WriteLine(" Change for " + inAmount + " is: ");
if (inAmount > 1.0)
{
Console.WriteLine("Number of dollars: " + Convert.ToInt32(inAmount));
}
MyMoney.PrintChange(coins);
Console.ReadKey();
}
}
}
You declared coins to be an array going from 0 to 2
array[size] //size is how many elements are in the array, not the upper bound of the array
coins[3] //means the array contains three elements, elements: 0, 1, 2
//so you want:
int[] coins = new int[4]; //Goes from 0 to 3, elements: 0, 1, 2, 3
//This will allow you to later access:
//since coins[3] is the 4th element, this is as high as the array can go now
coins[3] = (int)(inAmount / 0.25);
Related
using System;
namespace FirstApplication
{
class Program
{
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
string category = Console.ReadLine();
double total = 0;
switch (category)
{
case "I":
total = bc(k, 6) * bc(n - k, k - 6) / bc(n, k);
Console.WriteLine("{0:F10}", total);
return;
case "II":
total = bc(k, 4) * bc(n - k, k - 4) / bc(n, k);
Console.WriteLine("{0:F10}", total);
return;
case "III":
total = bc(k, 2) * bc(n - k, k - 2) / bc(n, k);
Console.WriteLine("{0:F10}", total);
return;
}
Console.Read();
}
private static double bc(decimal n, decimal k)
{
if (k == 0 || k == n)
return 1;
return bc(n - 1, k - 1) + bc(n - 1, k);
}
}
}
I have a problem with my code.
The exercise is the following:
You participate at the lottery 6/49 with only one winning variant(simple) and you want to know what odds of winning you have:
-at category I (6 numbers)
-at category II (5 numbers)
-at category III (4 numbers)
Write a console app which gets from input the number of total balls, the number of extracted balls, and the category, then print the odds of winning with a precision of 10 decimals if you play with one simple variant.
For example if I input:
49
6
I
The result is ok, but when I input:
45
15
III
I don’t get any result.
Any suggestions what is wrong with my code?
I don't think there's anything wrong with your code. It just runs for a very long time, because you call bc with the same values again and again. I added a dictionary to store and lookup the values already calculated:
private static Dictionary<(int N, int K),double> knownValues = new Dictionary<(int N, int K),double>();
private static double bc(int n, int k)
{
var key = (n,k);
if (!knownValues.ContainsKey(key))
{
if (k == 0 || k == n)
{
knownValues.Add(key, 1);
}
else
{
knownvalues.Add(key, bc(n - 1, k - 1) + bc(n - 1, k));
}
}
return knownValues[key];
}
And it returns in < 6 seconds with the value 0.0364626616 for your 45,15,III input. Whether that is right, I don't know, but at least it terminates. Maybe your teacher wanted you to try this and learn about recursion and calculation times.
I have a program that is to calculate taxes for payroll. I need a for loop to write the last name, first name, dept, rate, hours, earnings, fica, fedtax, statetax and netpay. I'm not thrown any errors when I run the program and can't seem to find why my output only displays the last name. There are two .txt files, one is blank for output and the other is listed below.
This is the data content of my .txt file:
Adams Paul 3 9.75 40.00
Allen Cindy 2 11.45 48.00
Allen Sarah 4 10.30 40.00
Baker John 1 22.00 43.25
Baker Toni 1 12.65 40.00
Baldwin Cindy 2 7.90 25.50
Carson Robert 1 8.35 52.50
Freeman Sally 4 15.25 40.00
Garfield James 3 22.00 40.00
Grimes Kerri 3 16.50 35.00
Harris Joan 2 18.65 51.00
Harris John 2 9.00 47.50
Lawson LeAnn 4 17.85 40.00
Mason Debbie 4 22.00 41.50
Masters Kenneth 3 16.10 40.25
Patterson Roseanne 2 13.70 38.00
Peterson Paul 2 22.00 44.00
Randall Michael 3 8.00 41.00
Rogers Sherry 1 16.50 30.00
Shepard Steven 3 10.90 45.50
This is my code:
using System;
using System.IO;
using System.Text.RegularExpressions;
using LibUtil;
classPayRoll
{
const double FICA_RATE = 0.07;
const double FED_TAX_RATE = 0.22;
const double STATE_TAX_RATE = 0.05;
const string INPUT_FILE_NAME = "PayrollDat.Txt";
const string OUTPUT_FILE_NAME = "PayrollReport.Txt";
static uint numOfEmployees;
static string[] lastNameArray = new string[51], firstNameArray = new string[51];
static uint[] deptArray = new uint[51];
static double[] rateArray = new double[51], hoursArray = new double[51];
static double[] earningsArray = new double[51], ficaArray = new double[51];
static double[] fedTaxArray = new double[51], stateTaxArray = new double[51];
static double[] netPayArray = new double[51];
static StreamReader fileIn;
static StreamWriter fileOut;
static void Main()
{
OpenFiles();
InputData();
CalcDetailPayroll();
PrintReport();
CloseFiles();
}
static void OpenFiles()
{
if (File.Exists(INPUT_FILE_NAME))
{
fileIn = File.OpenText(INPUT_FILE_NAME);
Console.WriteLine("{0} was opened", INPUT_FILE_NAME);
}
else
{
Console.WriteLine("Error: {0} does not exist\n", INPUT_FILE_NAME);
ConsoleApp.Exit();
}
fileOut = File.CreateText(OUTPUT_FILE_NAME);
if (File.Exists(OUTPUT_FILE_NAME))
Console.WriteLine("{0} was created\n", OUTPUT_FILE_NAME);
else
{
Console.WriteLine("Error: {0} could not be created\n", OUTPUT_FILE_NAME);
ConsoleApp.Exit();
}
}
static void ParseLineIn(string lineIn, uint i)
{
string[] words = new string[5];
lineIn = lineIn.Trim();
while (Regex.IsMatch(lineIn, "[ ]{2}"))
lineIn = lineIn.Replace(" ", " ");
words = lineIn.Split(' ');
lastNameArray[i] = words[0];
i = 0;
while (i <= numOfEmployees)
{
lastNameArray[i] = words[0];
firstNameArray[i] = words[1];
deptArray[i] = uint.Parse(words[2]);
rateArray[i] = double.Parse(words[3]);
hoursArray[i] = double.Parse(words[4]);
i++;
}
//Add code to read in data into remaining arrays
}
static void InputData()
{
uint i;
string lineIn;
i = 0;
while ((lineIn = fileIn.ReadLine()) != null)
{
i++;
ParseLineIn(lineIn, i);
}
numOfEmployees = i;
}
static void CalcDetailPayroll()
{
uint i;
double basePay, ovtPay;
for (i = 1; i <= numOfEmployees; i++)
{
if (hoursArray[i] <= 40.0)
{
basePay = Math.Round(hoursArray[i] * rateArray[i]); //Calculate base pay
ovtPay = 0.00;
}
else
{
basePay = Math.Round(40 * rateArray[i]); //Calculate base pay
ovtPay = Math.Round(rateArray[i] * (hoursArray[i] - 40.0) * 1.5); //Calculate overtime pay
}
//Calculate earnings, fica, fedTax, stateTax, and netPay
earningsArray[i] = basePay + ovtPay;
ficaArray[i] = earningsArray[i] * FICA_RATE;
fedTaxArray[i] = earningsArray[i] * fedTaxArray[i];
stateTaxArray[i] = earningsArray[i] * STATE_TAX_RATE;
netPayArray[i] = earningsArray[i] - (ficaArray[i] + fedTaxArray[i] + stateTaxArray[i]);
}
}
static double Total(double[] doubleArray)
{
uint i;
double total = 0.0;
for (i = 1; i <= numOfEmployees; i++) ;
total += earningsArray[i];
return total;
}
static double Mean(double[] doubleArray)
{
uint i;
double sum = 0.0;
for (i = 1; i <= numOfEmployees; i++)
sum += doubleArray[i];
return sum / numOfEmployees;
}
static double Max(double[] doubleArray)
{
uint i;
double max;
max = doubleArray[1];
for (i = 2; i <= numOfEmployees; i++)
if (doubleArray[i] > max)
max = doubleArray[i];
return max;
}
static double Min(double[] doubleArray)
{
uint i;
double min;
double max;
min = doubleArray[1];
for (i = 2; i <= numOfEmployees; i++)
if (doubleArray[i] < min)
max = doubleArray[i];
return min;
}
static void PrintReport()
{
uint i;
fileOut.WriteLine(" Payroll Report ");
fileOut.WriteLine();
fileOut.WriteLine(" Last Name First Name Dept Rate Hours Earnings FICA Fed Tax State Tax Net Pay ");
fileOut.WriteLine("--------------- --------------- ---- ----- ----- --------- --------- --------- --------- ---------");
for (i = 1; i <= numOfEmployees; i++)
{
fileOut.WriteLine("{0,-9} {1,9} {2,9} {3,9} {4,9} {5,9} {6,9} {7,9} {8,9} {9,9}",
lastNameArray[i], firstNameArray[i], deptArray[i], rateArray[i],hoursArray[i],earningsArray[i],
ficaArray[i],fedTaxArray[i],stateTaxArray[i],netPayArray[i]);
}
//Create for loop to display last name, firstname, dept, rate, hours, earnings, fica, fedTax, stateTax, and netPay
fileOut.WriteLine(" --------- --------- --------- --------- ---------");
fileOut.WriteLine("{0,-49}{1,9:n} {2,9:n} {3,9:n} {4,9:n} {5,9:n}",
"Total", Total(earningsArray), Total(ficaArray),
Total(fedTaxArray), Total(stateTaxArray), Total(netPayArray));
fileOut.WriteLine("{0,-49}{1,9:n} {2,9:n} {3,9:n} {4,9:n} {5,9:n}",
"Mean", Mean(earningsArray), Mean(ficaArray),
Mean(fedTaxArray), Mean(stateTaxArray), Mean(netPayArray));
fileOut.WriteLine("{0,-49}{1,9:n} {2,9:n} {3,9:n} {4,9:n} {5,9:n}",
"Maximum", Max(earningsArray), Max(ficaArray),
Max(fedTaxArray), Max(stateTaxArray), Max(netPayArray));
fileOut.WriteLine("{0,-49}{1,9:n} {2,9:n} {3,9:n} {4,9:n} {5,9:n}",
"Minimum", Min(earningsArray), Min(ficaArray),
Min(fedTaxArray), Min(stateTaxArray), Min(netPayArray));
}
static void CloseFiles()
{
fileIn.Close(); fileOut.Close();
}
}
You should change the ParseLineIn method to use the index passed from the caller. Actually you are setting always the same index when you set the i to zero
static void ParseLineIn(string lineIn, uint i)
{
string[] words = new string[5];
lineIn = lineIn.Trim();
while (Regex.IsMatch(lineIn, "[ ]{2}"))
lineIn = lineIn.Replace(" ", " ");
words = lineIn.Split(' ');
lastNameArray[i] = words[0];
// i = 0;
// No loop needed, you are reading one line of data and setting
// the appropriate index in the arrays
// while (i <= numOfEmployees)
//{
lastNameArray[i] = words[0];
firstNameArray[i] = words[1];
deptArray[i] = uint.Parse(words[2]);
rateArray[i] = double.Parse(words[3]);
hoursArray[i] = double.Parse(words[4]);
// i++;
//}
}
Also notice that your Total method has an error in this line
for (i = 1; i <= numOfEmployees; i++) ;
remove the semicolon at the end of the for loop to allow the execution of the line the makes the sum.
Said all this, I really suggest you to discard this array approach and build a proper class that represent your data and collect the information in a List of such data. Actually your code allows only files with 50 lines and please remember that array in NET start at index zero.
I am following instructions in a C# Tutorial video that is great. I am building a file with the notes and code from the video.
I reviewed similar questions but they do not solve this problem.
Here is a copy of the CS file:
static void Main(string[] args)
{
// Single line comments
/* test multi-line comments
* asldkjasldkjaskd
* asldkjasldkja
* alsdkjalksdj
* */
Console.WriteLine("Hello world!");
Console.Write("What is your name? ");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
bool canVote = true;
char grade = 'A';
// Integer with a max number of 2,147,483,647
int maxInt = int.MaxValue;
//Long with max value of 9,223,372,036,854,775,807
long maxLong = long.MaxValue;
// Decimal has a max value of 79,228,162,514,264,337,593,543,950,335
// If you need something bigger, look up BigInteger
decimal maxDecimal = decimal.MaxValue;
// A float is a 32 bit number with a max value of 3.402823E+38 with 7 decimal positions
float maxFloat = float.MaxValue;
// A double is a 32 bit number with a max value of 1.797693134E+308 with 15 decimal positions
double maxDouble = double.MaxValue;
Console.WriteLine("Max Int : " + maxInt);
Console.WriteLine("Max Long : " + maxLong);
Console.WriteLine("Max Decimal : " + maxDecimal);
Console.WriteLine("Max Float : " + maxFloat);
Console.WriteLine("Max Double : " + maxDouble);
var anotherName = "Tom";
// anotherName = 2; Cannot implicitly convert a gype 'int' to a 'string'
Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode());
// Math
Console.WriteLine("5 + 3 = " + (5 + 3));
Console.WriteLine("5 - 3 = " + (5 - 3));
Console.WriteLine("5 * 3 = " + (5 * 3));
Console.WriteLine("5 / 3 = " + (5 / 3));
Console.WriteLine("5.2 % 3 = " + (5.2 % 3));
int i = 0;
Console.WriteLine("i++ = " + (i++));
Console.WriteLine("++i = " + (++i));
Console.WriteLine("i-- = " + (i--));
Console.WriteLine("--i = " + (--i));
Console.WriteLine("i +- 3 = " + (i +- 3));
Console.WriteLine("i -= 2 = " + (i -= 2));
Console.WriteLine("i *= 2 = " + (i *= 2));
Console.WriteLine("i /= 2 = " + (i /= 2));
Console.WriteLine("i %= 2 = " + (i %= 2));
// casting
// if no magnitude is lost, casting will happen automatically. But otherwise, you set it up as follows
double pi = 3.14;
int intPi = (int)pi;
Console.WriteLine("intPi = " + intPi);
// Math functions
// Acos, Asin, Atan, Atan2, Cos, Cosh, Exp, Log, Sin, Sinh, Tan, Tanh
double number1 = 10.5;
double number2 = 15;
Console.WriteLine("number1 is " + number1);
Console.WriteLine("number2 is " + number2);
Console.WriteLine("Math.Abs(number1) " + (Math.Abs(number1)));
Console.WriteLine("Math.Ceiling(number2) " + (Math.Ceiling(number1)));
Console.WriteLine("Math.Floor(number1) " + (Math.Floor(number1)));
Console.WriteLine("Math.Max(number1,number2) " + (Math.Max(number1,number2)));
Console.WriteLine("Math.Min(number1,number2) " + (Math.Min(number1,number2)));
Console.WriteLine("Math.Pow(number1, 2) " + (Math.Pow(number1, 2)));
Console.WriteLine("Math.Round(number1) " + (Math.Round(number1)));
Console.WriteLine("Math.Sqrt(number1) " + (Math.Sqrt(number1)));
// random numbers
Random rand = new Random();
Console.WriteLine("Random number between 1 and 10 is " + rand.Next(1, 11));
// Relational operators : > < >= <= == !=
// Logical operators : && || ^ !
// note: ^ is the exclusive or
Console.WriteLine("What is your child's age? (enter 0 - 18)");
int age = Console.Read();
if ((age >= 5) && (age <= 7))
{
Console.WriteLine("Go to Elementary School");
} else if ((age > 7) && (age <= 13))
{
Console.WriteLine("Go to middle school");
} else if ((age < 5) || (age > 13))
{
Console.WriteLine("Your child does not meet our age requirements.");
} else
{
Console.WriteLine("Go to high school");
}
Console.WriteLine("What is your age? ");
int workingAge = Console.Read();
if ((workingAge < 14) || (workingAge > 67))
{
Console.WriteLine("You shouldn't work.");
}
}
The program ignores the input from the following:
Console.WriteLine("What is your age? ");
int workingAge = Console.Read();
The output is:
What is your age?
You shouldn't work.
So, the program is not stopping for my input, but rather seems to process its conditions based on the previous integer input value of 2 or 5.
Other articles talked about doing the following which I tried with no avail:
Console.WriteLine("What is your age? ");
int workingAge = Convert.ToInt32(Console.Read());
And
Console.WriteLine("What is your age? ");
int workingAge = int32.Parse(Console.Read());
The second one produced an error in Visual Studio The name 'int32' does not exist in the current context
I updated the script to use int.Parse(Console.ReadLine()), and it worked on Visual Studio 2007, but I ran this on Visual Studio 2015 Community Edition and it is doing the same exact thing as if the changes had no effect:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Single line comments
/* test multi-line comments
* asldkjasldkjaskd
* asldkjasldkja
* alsdkjalksdj
* */
Console.WriteLine("Hello world!");
Console.Write("What is your name? ");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
bool canVote = true;
char grade = 'A';
// Integer with a max number of 2,147,483,647
int maxInt = int.MaxValue;
//Long with max value of 9,223,372,036,854,775,807
long maxLong = long.MaxValue;
// Decimal has a max value of 79,228,162,514,264,337,593,543,950,335
// If you need something bigger, look up BigInteger
decimal maxDecimal = decimal.MaxValue;
// A float is a 32 bit number with a max value of 3.402823E+38 with 7 decimal positions
float maxFloat = float.MaxValue;
// A double is a 32 bit number with a max value of 1.797693134E+308 with 15 decimal positions
double maxDouble = double.MaxValue;
Console.WriteLine("Max Int : " + maxInt);
Console.WriteLine("Max Long : " + maxLong);
Console.WriteLine("Max Decimal : " + maxDecimal);
Console.WriteLine("Max Float : " + maxFloat);
Console.WriteLine("Max Double : " + maxDouble);
var anotherName = "Tom";
// anotherName = 2; Cannot implicitly convert a gype 'int' to a 'string'
Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode());
// Math
Console.WriteLine("5 + 3 = " + (5 + 3));
Console.WriteLine("5 - 3 = " + (5 - 3));
Console.WriteLine("5 * 3 = " + (5 * 3));
Console.WriteLine("5 / 3 = " + (5 / 3));
Console.WriteLine("5.2 % 3 = " + (5.2 % 3));
int i = 0;
Console.WriteLine("i++ = " + (i++));
Console.WriteLine("++i = " + (++i));
Console.WriteLine("i-- = " + (i--));
Console.WriteLine("--i = " + (--i));
Console.WriteLine("i +- 3 = " + (i + -3));
Console.WriteLine("i -= 2 = " + (i -= 2));
Console.WriteLine("i *= 2 = " + (i *= 2));
Console.WriteLine("i /= 2 = " + (i /= 2));
Console.WriteLine("i %= 2 = " + (i %= 2));
// casting
// if no magnitude is lost, casting will happen automatically. But otherwise, you set it up as follows
double pi = 3.14;
int intPi = (int)pi;
Console.WriteLine("intPi = " + intPi);
// Math functions
// Acos, Asin, Atan, Atan2, Cos, Cosh, Exp, Log, Sin, Sinh, Tan, Tanh
double number1 = 10.5;
double number2 = 15;
Console.WriteLine("number1 is " + number1);
Console.WriteLine("number2 is " + number2);
Console.WriteLine("Math.Abs(number1) " + (Math.Abs(number1)));
Console.WriteLine("Math.Ceiling(number2) " + (Math.Ceiling(number1)));
Console.WriteLine("Math.Floor(number1) " + (Math.Floor(number1)));
Console.WriteLine("Math.Max(number1,number2) " + (Math.Max(number1, number2)));
Console.WriteLine("Math.Min(number1,number2) " + (Math.Min(number1, number2)));
Console.WriteLine("Math.Pow(number1, 2) " + (Math.Pow(number1, 2)));
Console.WriteLine("Math.Round(number1) " + (Math.Round(number1)));
Console.WriteLine("Math.Sqrt(number1) " + (Math.Sqrt(number1)));
// random numbers
Random rand = new Random();
Console.WriteLine("Random number between 1 and 10 is " + rand.Next(1, 11));
// Relational operators : > < >= <= == !=
// Logical operators : && || ^ !
// note: ^ is the exclusive or
Console.WriteLine("What is your child's age? (enter 0 - 18)");
int age = int.Parse(Console.ReadLine());
if ((age >= 5) && (age <= 7))
{
Console.WriteLine("Go to Elementary School");
}
else if ((age > 7) && (age <= 13))
{
Console.WriteLine("Go to middle school");
}
else if ((age < 4) || (age > 18))
{
Console.WriteLine("Your child does not meet our age requirements.");
}
else
{
Console.WriteLine("Go to high school");
}
Console.WriteLine("What is your age? ");
int workingAge = int.Parse(Console.ReadLine());
if ((workingAge < 14) || (workingAge > 67))
{
Console.WriteLine("You shouldn't work.");
}
else
{
Console.WriteLine("Work harder and smarter to get ahead.");
}
}
}
}
Please help.
.Read() reads only a single character. You probably want .ReadLine() instead, which reads all the characters up to Enter, and returns a string.
int workingAge = int.Parse(Console.ReadLine());
Expanding off of #recursive you can use int32.TryParse() to check if a valid number was supplied.
bool valid = false;
int workingAge;
while (!valid)
{
valid = int32.TryParse(Console.ReadLine(), out workingAge);
if (!valid)
Console.WriteLine("Supplied number was invalid");
}
// Rest of code
Edit: I think this can be simplified even further by doing the following:
int workingAge;
while (!int32.TryParse(Console.ReadLine(), out workingAge))
{
Console.WriteLine("Supplied number was invalid");
}
// Rest of code
I will add to recursive's solution and explain what is happening.
since you are using Console.Read() in two different areas -
and since Console.Read() reads one key input (i.e '1') -
you are probably entering two different digits in the first occurance which causes the first .Read() to only read the first digit, and "passes" the second digit to the second .Read()
as was said before me, changing the .Read() to .ReadLine() will solve your issue.
I'm studying coding and I'm on project 8 of project euler.
I was able to show the product "5832" for four adjacent digits when I'm using my code however when I use it on 13 digits, it doesn't work. My code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practice
{
class Program
{
static void Main(string[] args)
{
const string number = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
string input1, input2, input3, input4, input5;
string input6, input7, input8, input9, input10;
string input11, input12, input13;
int convert1, convert2, convert3, convert4, convert5;
int convert6, convert7, convert8, convert9, convert10;
int convert11, convert12, convert13;
convert1 = convert2 = convert3 = convert4 = convert5 = convert6 = convert7 = convert8 = 0;
convert9 = convert10 = convert11 = convert12 = convert13 = 0;
int counter;
int product = 0;
int largest = 0;
int length = number.Length - 13;
for (counter = 1; counter <= length; counter++)
{
input1 = number.Substring(counter, 1);
input2 = number.Substring(counter+1, 1);
input3 = number.Substring(counter+2, 1);
input4 = number.Substring(counter+3, 1);
input5 = number.Substring(counter+4, 1);
input6 = number.Substring(counter+5, 1);
input7 = number.Substring(counter+6, 1);
input8 = number.Substring(counter+7, 1);
input9 = number.Substring(counter+8, 1);
input10 = number.Substring(counter+9, 1);
input11 = number.Substring(counter+10, 1);
input12 = number.Substring(counter+11, 1);
input13 = number.Substring(counter+12, 1);
convert1 = Convert.ToInt32(input1);
convert2 = Convert.ToInt32(input2);
convert3 = Convert.ToInt32(input3);
convert4 = Convert.ToInt32(input4);
convert5 = Convert.ToInt32(input5);
convert6 = Convert.ToInt32(input6);
convert7 = Convert.ToInt32(input7);
convert8 = Convert.ToInt32(input8);
convert9 = Convert.ToInt32(input9);
convert10 = Convert.ToInt32(input10);
convert11 = Convert.ToInt32(input11);
convert12 = Convert.ToInt32(input12);
convert13 = Convert.ToInt32(input13);
product = convert1 * convert2 * convert3 * convert4 * convert5 * convert6
* convert7 * convert8 * convert9 * convert10 * convert11
* convert12 * convert13;
if (largest < product) { largest = product; }
}
Console.WriteLine("The largest number is {0}", largest);
Console.ReadKey();
}
}
}
It doesn't show the correct answer which I find daunting. The next steps
I did is:
1. Check the last 13 digits of my variables to check if it loops and multiplies correctly "0420420752963450".
2. Check if it works with the first four numbers and first five numbers which are surprisingly correct.
3. Studied how others have done it.
4. Links used:
Homework in Java. Find the largest product of five consecutive digits
http://www.mathblog.dk/solution-to-problem-8-of-project-euler/
I seem to not get it. Please guide me on seeing my mistake. Thank you.
Your product variable is int and you parse your consecutive numbers to int. Max value for integer is 2,147,483,647. So when you multiply 13 numbers it's quite possible you will exceed the limit and the value will overflow giving incorrect result. Perhaps, consider using BigInteger instead.
What about something like this:
[Test]
public void Test()
{
const string number = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int index = 0;
int largest = 0;
var largestString = "";
const int length = 13;
while (index + length <= number.Length)
{
var substring = number.Substring(index, length);
var product = ProductOfEachNumber(substring);
if (product > largest)
{
largestString = substring;
largest = product;
}
index++;
}
Console.WriteLine("The largest number is {0}", largest);
Console.WriteLine("The largest number string is {0}", largestString);
}
[Test]
public void TestSubstring()
{
var res = ProductOfEachNumber("9989");
res.Should().Be(5832);
}
private static int ProductOfEachNumber(string substring)
{
return substring.Aggregate(1, (current, c) => current*Int32.Parse(c.ToString()));
}
Gives output:
The largest number is 2091059712
The largest number string is 9781797784617
Try this one, let me know. You have to modify it.
static void Main(string[] args)
{
Stopwatch sw = Stopwatch.StartNew();
int x = Largest();
Console.WriteLine(x);
Console.WriteLine("Time used (float): {0} ms", sw.Elapsed.TotalMilliseconds);
Console.WriteLine("Time used (rounded): {0} ms", sw.ElapsedMilliseconds);
Console.ReadKey();
}
public static int Largest()
{
string p = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int largest = 0;
int numm = 0;
for (int i = 0; i < p.Length - 4; i++)
{
numm = int.Parse(p.Substring(i, 1)) *
int.Parse(p.Substring(i + 1, 1)) *
int.Parse(p.Substring(i + 2, 1)) *
int.Parse(p.Substring(i + 3, 1)) *
int.Parse(p.Substring(i + 4, 1));
if (numm > largest)
{
largest = numm;
}
}
return largest;
}
I have to write a "encryption" program for my C# intro class. I'm encountering 2 problems:
When a negative is entered or it calculates a negative during the decryption process, it crashes. - it returns and unhandled exception error: System.FormatException: Input string was not in a correct format.
The decryption should be the reverse of the encryption without using the original variable. How do you reverse a remainder calculation?
I know it's part of the do while loop that's the issue, I'm just not sure how to continue to prompt for a value if a negative is entered and if encountered during the decryption calculation to keep it from crashing. Any guidance would be much appreciated. Thanks for taking a look at it!
public class MainClass
{
public static void Main(string[] args)
{
int num = 0;
int dnum = 0;
do
{
Console.Write("Please enter a non-negative integer to encrypt: ");
num = Convert.ToInt32(Console.ReadLine());
string numstr = Convert.ToString(num);
string num1 = Convert.ToString(numstr.Substring(0, 1));
string num2 = Convert.ToString(numstr.Substring(1, 1));
string num3 = Convert.ToString(numstr.Substring(2, 1));
string num4 = Convert.ToString(numstr.Substring(3, 1));
int enum1 = ((Convert.ToInt32(num1) + 7) % 10);
int enum2 = ((Convert.ToInt32(num2) + 7) % 10);
int enum3 = ((Convert.ToInt32(num3) + 7) % 10);
int enum4 = ((Convert.ToInt32(num4) + 7) % 10);
Console.WriteLine("Encrypted Integer: {0:D4}", (1000 * enum3 + 100 * enum4 + 10 * enum1 + enum2));
Console.Write("Please enter a non-negative integer to decrypt: ");
dnum = Convert.ToInt32(Console.ReadLine());
string dnumstr = Convert.ToString(dnum);
string num1d = Convert.ToString(dnumstr.Substring(0, 1));
string num2d = Convert.ToString(dnumstr.Substring(1, 1));
string num3d = Convert.ToString(dnumstr.Substring(2, 1));
string num4d = Convert.ToString(dnumstr.Substring(3, 1));
int dnum1 = ((Convert.ToInt32(num1d) - 7) * 10);
int dnum2 = ((Convert.ToInt32(num2d) - 7) * 10);
int dnum3 = ((Convert.ToInt32(num3d) - 7) * 10);
int dnum4 = ((Convert.ToInt32(num4d) - 7) * 10);
Console.WriteLine("Decrypted Integer: {0:D4}", (1000 * dnum1 + 100 * dnum2 + 10 * dnum3 + dnum4));
} while (num > 0);
} // end Main
}// end class
The policy is, do not proceed until user enters a 'correct' input. Here is code sample, note that I use numstr[0] - an index to get the first char instead of numstr.Substring(0, 1) so the code looks cleaner.
int num = 0;
bool isValid = false;
do
{
Console.Write("Please enter 4 digits to encrypt: ");
string numstr = Console.ReadLine();
if (numstr.Length == 4)
{
isValid = Char.IsDigit(numstr[0]) && Char.IsDigit(numstr[1])
&& Char.IsDigit(numstr[2]) && Char.IsDigit(numstr[3]);
}
if (isValid)
num = Convert.ToInt32(input);
}
while (!isValid);
As for your 2nd question, you can't use multiplication to reverse a remainder calculation ((d+7)%10), you should again use remainder operator (d+10-7)%10, the additional 10 is added to keep it from getting negative result.
There is another bug in your decryption process, you can turn to your debugger for help.