Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Console App Programming Help 1

Status
Not open for further replies.

Mibble

IS-IT--Management
Sep 9, 2004
28
US
I have a simple application I am trying to put together, (newbie with C#, programming, etc)
The task is to have a number keyed in, then return the difference between Value A and Value B. (valuea is fixed at 100.00, valueb can be any number up to 100.00)
I need to return the number of quarters, dimes, nickels and pennies to return, ie if value is 23.21 (valueb), i take valuea minus valueb and figure out as above.
if an item has an empty value, then it does not get displayed, if pennies is only one, needs to be displayed as 1 penny.
i have this code below thus far, as i believe it will be done with a 'while' after converting from string to int.
that is where i am stuck at, the string to int value.

using System;
using System.Collections.Generic;
using System.Text;

namespace Assign1
{

class Program
{
public static void Main(string[] args)
{
int changeRequest = 0;
int numQuarters = 0;
int numDimes = 0;
int numNickels = 0;
int numPennies = 0;
string amntIn;
Console.WriteLine("Please enter your request. Numbers only, Format: XX.XX ");
amntIn = Console.ReadLine();
Console.WriteLine("The amount entered is: {0}", amntIn);

changeRequest = Convert.ToInt32(amntIn);
Console.WriteLine("Converted, the number is {0}", changeRequest);
changeRequest = changeRequest * 100;

while (changeRequest > 25)
{
changeRequest = changeRequest - 25;
numQuarters++;
}
Console.WriteLine("Value of changeRequest is: {0}", changeRequest);
Console.WriteLine("current value of quarters returned is {0}", numQuarters);
while (changeRequest > 10)
{
changeRequest = changeRequest - 10;
numDimes++;
}
while (changeRequest > 5)
{
changeRequest = changeRequest - 5;
numNickels++;
}
while (changeRequest > 1)
{
changeRequest = changeRequest - 1;
numPennies++;
}
Console.WriteLine("Your change is {0},{1},{2},{3}", numQuarters, numDimes, numNickels, numPennies);
}
}
}

Any help appreciated.
 
Can't help you too much, as this is an assignment. A clue, however;
Code:
23.21
Code:
[red]int[/red] changeRequest = 0;

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
i do have changeRequest set to int and at zero, one of the first lines.
 
Yes, that's exactly my point. What do you think happens when you try to parse "23.21" as an Int?

Just as a test, run your program and enter "23" when it prompts you...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
hey thanks Steve, that was a stupid mistake on my part.
this is what I have, and it works, other than looping through if to be done again and checking for numbers.

using System;
using System.Collections.Generic;
using System.Text;

namespace Assign1
{

class Program
{
public static void Main(string[] args)
{
// initialize variables
double changeRequest = 0.00;
int numQuarters = 0;
int numDimes = 0;
int numNickels = 0;
int numPennies = 0;
string amntIn;

// display request
Console.WriteLine("Please enter your request. Numbers only, Format: XX.XX ");

// get amount requested
amntIn = Console.ReadLine();

// troubleshooting line
Console.WriteLine("The amount entered is: {0}", amntIn);

// convert string to double
changeRequest = Convert.ToDouble(amntIn);

// troubleshooting line, verification on amount entered
Console.WriteLine("Converted, the number is {0}", changeRequest);

// convert to 100 times the amount, easier for subtraction
changeRequest = changeRequest * 100;

// start of counting the change
while (changeRequest >= 25)
{
changeRequest = changeRequest - 25;
numQuarters++;
}
//Console.WriteLine("Value of changeRequest is: {0}", changeRequest);
Console.WriteLine("current value of quarters returned is {0}", numQuarters);

while (changeRequest >= 10)
{
changeRequest = changeRequest - 10;
numDimes++;
}

while (changeRequest >= 5)
{
changeRequest = changeRequest - 5;
numNickels++;
}
while (changeRequest >= 1)
{
changeRequest = changeRequest - 1;
numPennies++;
}
if (numQuarters > 1)
Console.WriteLine("You have {0} quarters.", numQuarters);
if (numQuarters == 1)
Console.WriteLine("You have {0} quarter.", numQuarters);
else
{
}
if (numDimes > 1)
Console.WriteLine("You have {0} dimes.", numDimes);
if (numDimes == 1)
Console.WriteLine("You have {0} dime.", numDimes);
else
{
}
if (numNickels > 1)
Console.WriteLine("You have {0} nickels.", numNickels);
if (numNickels == 1)
Console.WriteLine("You have {0} nickel.", numNickels);
else
{
}
if (numPennies > 1)
Console.WriteLine("You have {0} pennies.", numPennies);
if (numPennies == 1)
Console.WriteLine("You have {0} penny.", numPennies);
else
{
}
// Console.WriteLine("Your change is {0},{1},{2},{3}", numQuarters, numDimes, numNickels, numPennies);
}
}
}
 
Mibble

Now you've done the assignment, I can give you a few tips. There is always more than one way to do it (as the perl folks will tell you). Your while loop scheme is fine as far as it goes, but it contains a lot of unnecessary iteration and duplicated code.

Division of one integer by another gives an integer result. So 25 / 6 = 4, and the remainder is ignored. The modulus operator allows you to ignore the result, and get the remainder, so 25 % 6 = 1.

You can use these two features to simplify your program. The following example goes a step further and makes use of arrays. But it still has the same lack of error handling as your original1.
Code:
using System;

namespace Assign1 {

   class ChangeGiver {

      public static void Main(string[] args) {
            
         int pennies = 0;
         int[] change = {0, 0, 0, 0};
         int[] divisor = {25, 10, 5, 1};
         string[] labels = {"quarter", "dime", "nickel", "penny"};
         string[] plural = {"quarters", "dimes", "nickels", "pennies"};
         string amntIn;

         Console.WriteLine("Please enter your request. Numbers only, Format: XX.XX ");
            
         amntIn = Console.ReadLine();
            
         // convert string
         pennies = Convert.ToInt32(Convert.ToDouble(amntIn) * 100);

         for (int i = 0; i < change.Length; i++) {

            change[i] = pennies / divisor[i];
            pennies = pennies % divisor[i];

            if (change[i] > 0) {
               Console.WriteLine("You have {0} {1}", change[i], 
                  change[i] == 1 ? labels[i] : plural[i]);
            }
            
         }

      }
   }
}

1 try entering a negative value or worse still 'abc', and see what happens...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
that is a whole lot less code! i need to delve in quite a bit! any recommended books to learn this?

with a negative #, it gives 'press any key ... and then exits.

i will get the validation worked on, then the loop!

thanks for your help, i will be back with what i find.
 
Programming C# by Jesse Liberty. Get the latest version. Covers all the basics in the first half, then builds a sample app in the second.

It exits on the negative number because of
Code:
if (change[i] [red]>[/red] 0) {
(technically, it doesn't exit - it still runs but doesn't print anything).

And it bombs big time if you enter a non-numeric.

Note: it would have been much simpler if the plural of penny was pennys...[smile]



Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
i have done some research, have added a few things.
this now validates for positive numbers only, if alpha, etc it now does not bomb. maybe i have too many things in here now. by changing the bank # i can change the display of the drawer amount. still working on if over bank or the while for looping until the customer wants to stop getting 'change'. each time it will reset back to the bank amount.

using System;
using System.Text.RegularExpressions;

namespace Assign1
{

class ChangeGiver
{

public static void Main(string[] args)
{
ChangeGiver objValidate = new ChangeGiver();
int bank = 20000;
int drawer = bank;
int pennies = 0;
int[] change = { 0, 0, 0, 0 };
int[] divisor = { 25, 10, 5, 1 };
string[] labels = { "quarter", "dime", "nickel", "penny" };
string[] plural = { "quarters", "dimes", "nickels", "pennies" };
string amntIn;

Console.WriteLine("Our bank is ${0}.00. Please enter your request. Numbers only, Format: XX.XX ", (bank*.01));

amntIn = Console.ReadLine();

//Validation to perform
if (objValidate.IsPositiveNumber(amntIn))
{
Console.WriteLine("{0} is Valid Entry", amntIn);
// convert string
pennies = Convert.ToInt32(Convert.ToDouble(amntIn) * 100);
// while (pennies <= bank)
// {
pennies = (drawer - pennies);

for (int i = 0; i < change.Length; i++)
{

change = pennies / divisor;
pennies = pennies % divisor;

if (change > 0)
{
Console.WriteLine("You have {0} {1}", change,
change == 1 ? labels : plural);
}
}
}

}
// }



// Function to Test for Positive Number both Integer & Real

public bool IsPositiveNumber(string strNumber)
{
Regex objNotPositivePattern = new Regex("[^0-9.]");
Regex objPositivePattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");

return !objNotPositivePattern.IsMatch(strNumber) &&
objPositivePattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber);
}
}
}
 
Good. I don't think you have too much in there, and pulling the validation out to a separate function is a nice way of keeping your code clean. It also allows you to experiment with different ways of doing it such as a try-catch block for example, although I quite like your regex solution (but I would, I'm a bit of a regex head anyway).

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
What is the name of the class. cis??? is it college? I am just curios. Is the class teaching structured programming, OOP, ....?
Marty
 
it is a c# class, college 200 level class. first assignment is via console, i think the rest will be windows applications.
one of the others i am in, is where a blog application needs to be written for asp 2.0 which is also a 200 level class.
 
Thank you for the reply and I hope you ace the course. You may want to consider giving Steve a star.
Marty
 
Ok, I believe this is it. May be round about to get it to ask yes/no and exit, however it works! Any comments/shortcuts welcomed.
Thanks to Steve for helping me, and after I got it figured out the first time, he gave a great shortcut, made me think of all different ways!

using System;
using System.Text.RegularExpressions;

namespace Assign1
{

class ChangeGiver
{
static void Welcome()
{
ChangeGiver objValidate = new ChangeGiver();
int bank = 20000;
int pennies = 0;
int[] change = { 0, 0, 0, 0 };
int[] divisor = { 25, 10, 5, 1 };
string[] labels = { "quarter", "dime", "nickel", "penny" };
string[] plural = { "quarters", "dimes", "nickels", "pennies" };
string amntIn;

Console.WriteLine("Our bank is ${0}.00. Please enter your request. Numbers only, Format: XX.XX ", (bank * .01));

amntIn = Console.ReadLine();


//Validation to perform
if (objValidate.IsPositiveNumber(amntIn))
{
//Console.WriteLine("{0} is a Valid Entry", amntIn);
// convert string
pennies = Convert.ToInt32(Convert.ToDouble(amntIn) * 100);

if (pennies > bank)
{
Console.WriteLine("You have exceeded the bank.");

Welcome();
}

for (int i = 0; i < change.Length; i++)
{

change = pennies / divisor;
pennies = pennies % divisor;

if (change > 0)
{
Console.WriteLine("You have {0} {1}", change,
change == 1 ? labels : plural);
}
}
}
else
Console.WriteLine("Invalid characters.");
GetPosition();
}

public static void Main(string[] args)
{

Welcome();

}

// Function to Test for Positive Number both Integer & Real

public bool IsPositiveNumber(string strNumber)
{
Regex objNotPositivePattern = new Regex("[^0-9.]");
Regex objPositivePattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");

return !objNotPositivePattern.IsMatch(strNumber) &&
objPositivePattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber);
}

static string GetPosition()
{
char Position;

Console.Write("More change(y/n)? ");
string Pos = Console.ReadLine();
Position = char.Parse(Pos);

if (Position == 'y' || Position == 'Y')
Welcome();
else if (Position == 'n' || Position == 'N')
Console.WriteLine("Thanks!");
return "Thanks!";
}

}
}
 
Mibble

In a moment of boredom I played around with your regex checking and came up with
Code:
private static bool validateInput(string s) {

   Regex r = new Regex(@"^\d+(\.\d{1,2})?$");
   return r.IsMatch(s);
}
which allows 9999, 9.99 and 9.9 but not -9, .99 or 9.999

This is probably more restrictive than you really need, but it is a bit simpler...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
yes, much simpler and works properly. thanks! i just have to brush up on my programming skills. i first took C in 1986, then never used it.
 
i was doing some testing, if you enter 2.224 (what i used) on the first time in, it gets seen correctly as invalid. upon saying y and enter in 2.24 it crashes.
 
ok found out it is when i check for y/n, if i enter two characters it crashes.
unhandled exception: system.format.exceptioin: string must be exactly one character at system.char.parse(string s)

i didnt put the caps in the line where they go, however i hope you get my jist.
John
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top