Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Jan 21st, 2007, 9:23 PM   #1
mrynit
Hobbyist Programmer
 
mrynit's Avatar
 
Join Date: Mar 2006
Location: WA, USA
Posts: 332
Rep Power: 3 mrynit is on a distinguished road
Send a message via AIM to mrynit Send a message via MSN to mrynit Send a message via Yahoo to mrynit Send a message via Skype™ to mrynit
error trappring and looping

the code below is a simple menu driven program to calculate loan stuffs. i have to beable to trap bad user input and tie that with looping of the program. also the main goal of this assignmnet is to use methods. there are my problems

1. in displayMenu(),as it is now, the user must pick a letter from the menu but what if the use picks a bad letter? i have to trap bad input, tell the use that it was a bad input and then get good input. i know this involves some sorta loop and conditional. i dont know how to test input if it is not P,I,T or Q and loop based on that.


java Syntax (Toggle Plain Text)
  1. import java.util.Scanner; //console I/O
  2. import java.util.Currency; //dollar format
  3. import java.util.Locale; //get defual location info (US)
  4. import java.text.NumberFormat; //numerical formating
  5.  
  6.  
  7. public class Assignment1b
  8. {
  9. //intialize new scanner object as global so other methods can use it
  10. //is there a better way to do this? should ask Hoagland.
  11. static Scanner scanner = new Scanner(System.in);
  12.  
  13. public static void main(String[] args)
  14. {
  15. //displays the menu and returns a valid user selection
  16. char choice = displayMenu();//hold menu choice
  17. //print the cost by calling other functions
  18. loanCaculator(choice);
  19.  
  20. }
  21.  
  22. //foobar. need to error check for bad inputs in some sorta loop i dont know how.
  23. public static char displayMenu()
  24. {
  25. System.out.println(" Loan Caluclator");
  26. System.out.println("**************************");
  27. System.out.println("Calulate monthly (P)ayment");
  28. System.out.println("Calulate total (I)ntrest");
  29. System.out.println("Calulate total (L)oan");
  30. System.out.println("to exit program (Q)uit\n");
  31. System.out.print("Select P,I,L or Q: ");
  32.  
  33. String stringInput = scanner.next();
  34. char charInput = Character.toUpperCase(stringInput.charAt(0));
  35.  
  36.  
  37. switch(charInput)
  38. {
  39. /*Fall thru on purpose. these are blank b/c if the user enters such
  40.   values they are valid and will be returened out side the switch
  41.   statement. other wise all non P,I,T,Q values will be caught
  42.   as bad values and not be returned.*/
  43. case 'P':
  44. case 'I':
  45. case 'T':
  46. break;
  47.  
  48. //return Q to main so loop the whole program in main
  49. case 'Q':
  50. System.out.println("Exiting program....\n");
  51. System.exit(0);
  52. break;
  53.  
  54. default:
  55. System.out.println("No vaild entry.Run again using only P, I, T or Q\n");
  56. break;
  57. }
  58. return charInput;
  59. }
  60.  
  61. public static void loanCaculator(char choice)
  62. {
  63. //intialize new US currency format
  64. NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
  65.  
  66. System.out.print("Enter the principle of the loan: ");
  67. double amount = scanner.nextDouble();
  68.  
  69. double rate = 0.0;//scope
  70. do
  71. {
  72. System.out.print("Enter the intrest rate between 1% and 100%: ");
  73. rate = scanner.nextDouble();
  74. }
  75. while(rate > 100.0 || rate < 1.0);
  76.  
  77. System.out.print("Enter the term of loan: ");
  78. double term =scanner.nextDouble();
  79.  
  80. System.out.print("The total cost is ");
  81.  
  82. switch(choice)
  83. {
  84. case 'P':
  85. System.out.println(nf.format(calcPayment(amount, rate, term)));
  86. break;
  87.  
  88. case 'I':
  89. System.out.println(nf.format(clacIntrest(amount, rate, term)));
  90. break;
  91.  
  92. case 'T':
  93. System.out.println(nf.format(calcTotalLoan(amount, rate, term)));
  94. break;
  95. }
  96. }
  97.  
  98. public static double calcPayment(double amount, double rate, double term)
  99. {
  100. return (amount * rate) / (1.0 - Math.pow((1.0 + rate), (-term)));
  101. }
  102.  
  103. public static double clacIntrest(double amount, double rate, double term)
  104. {
  105. return term * calcPayment(amount, rate, term) - amount;
  106. }
  107.  
  108. public static double calcTotalLoan(double amount, double rate, double term)
  109. {
  110. return amount + clacIntrest(amount, rate, term);
  111. }
  112.  
  113. }
__________________
i dont know much about programming but i try to help
mrynit is offline   Reply With Quote
Old Jan 21st, 2007, 9:41 PM   #2
Serinth
Programmer
 
Serinth's Avatar
 
Join Date: Sep 2005
Posts: 50
Rep Power: 4 Serinth is on a distinguished road
you need to throw the menu into a loop and not break out of it if it hits the default switch statement.
__________________
A girl talked to me once.

http://www.latestanime.com
Serinth is offline   Reply With Quote
Old Jan 21st, 2007, 10:21 PM   #3
mrynit
Hobbyist Programmer
 
mrynit's Avatar
 
Join Date: Mar 2006
Location: WA, USA
Posts: 332
Rep Power: 3 mrynit is on a distinguished road
Send a message via AIM to mrynit Send a message via MSN to mrynit Send a message via Yahoo to mrynit Send a message via Skype™ to mrynit
Quote:
Originally Posted by Serinth View Post
you need to throw the menu into a loop and not break out of it if it hits the default switch statement.
some thing like this?
java Syntax (Toggle Plain Text)
  1. import java.util.Scanner;
  2.  
  3. public class Test3
  4. {
  5. public static void main(String[] args)
  6. {
  7. //intialize new scanner object
  8. Scanner scanner = new Scanner(System.in);
  9.  
  10. boolean repete = false;
  11. char charInput;
  12. String stringInput = "";
  13.  
  14. do
  15. {
  16. System.out.println(" Loan Caluclator");
  17. System.out.println("**************************");
  18. System.out.println("Calulate monthly (P)ayment");
  19. System.out.println("Calulate total (I)ntrest");
  20. System.out.println("Calulate total (L)oan");
  21. System.out.println("to exit program (Q)uit\n");
  22. System.out.print("Select P,I,L or Q: ");
  23.  
  24. stringInput = scanner.next();
  25. charInput = Character.toUpperCase(stringInput.charAt(0));
  26.  
  27. switch(charInput)
  28. {
  29. case 'P':
  30. case 'I':
  31. case 'L':
  32. repete = false;
  33. break;
  34.  
  35. //return Q to main so loop the whole program in main
  36. case 'Q':
  37. System.out.println("Exiting program....\n");
  38. System.exit(0);
  39. break;
  40.  
  41. default:
  42. System.out.println("No vaild entry.Run again using only P, I, T or Q\n");
  43. repete = true;
  44. }
  45. }
  46. while(repete);
  47.  
  48. System.out.println(charInput);
  49. }
  50. }
it works but my teacher says not to use flags.
__________________
i dont know much about programming but i try to help
mrynit is offline   Reply With Quote
Old Jan 21st, 2007, 10:34 PM   #4
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
This is not so much a language issue as it is a design issue. User input devices rarely, if ever, give you directly useful information. They provide binary patterns that indicate that this or that key was pressed, or this or that point on the screen was touched, or whatever. Your machine is not smart. It is merely a reactive device constrained by its hardware implementation.

Your machine has little, if any, utility, out of the box. Free (seemingly) utility comes from those who have decided, for whatever reason, to make your job easier.

When you press a key (if you have keys) on your device, it doesn't matter if that key is labeled "ENTER", or "BOINK MY WIFE". That key produces a binary output. Someone gets to determine what it means.

In the most common systems available to novices today (desktop/laptop machines), this is a two-step process, or more. The input device produces a code. The OS converts this code to some other code or sequence of codes. The language (which has to be defined, implementation-wise) for that OS converts this other code to some other code, or sequence of codes. The user of that language has to decide whether this latter code represents, say, text, or a number, or some control mechanism. Fortunately, for most users, someone else has done that. Your responsibility is to read what that someone else has said about how that code, so thoughtfully provided, works. Two people working for you may have different ideas.

User input is particularly invidious. If you're reading a file, you might have failures because of your own errors, or a corrupt file, or a broken mechanism. With human users, one has the added burden of dealing with inattention, stupidity, maliciousness, or a number of other things. You must know what you're writing, or what your utilities think of certain kinds of input, and how they deal with it.

Failing to contend with this situation is, at best, ignorance. At worst, it's negligence or overt malice. Such actions may subject you to no penalties whatsoever. They could conceivably subject you to rather harsh penalties meted out in a court of civil or criminal justice.

Budding professionals need to think about and deal with these things. Read your documentation with an eye for your concerns.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Jan 22nd, 2007, 4:46 AM   #5
mrynit
Hobbyist Programmer
 
mrynit's Avatar
 
Join Date: Mar 2006
Location: WA, USA
Posts: 332
Rep Power: 3 mrynit is on a distinguished road
Send a message via AIM to mrynit Send a message via MSN to mrynit Send a message via Yahoo to mrynit Send a message via Skype™ to mrynit
I took some time to review a few things and came up with this. I would like your comments and suggestions for making the code more effient and "better". thanks for the help so far.

java Syntax (Toggle Plain Text)
  1. /*
  2. Author: *mrynit*
  3. Date made: 1-20-07
  4. last update: 1-22-07
  5. Purpose: provide a menue based program to calculate various loan related values.
  6. the main method loops untill user selects the exit command. there is error trapping
  7. for bad menue opptions and rate that is not between 1% and 100%. all other inputs
  8. are not tested for invalid input.
  9. */
  10.  
  11. import java.util.Scanner; //console I/O
  12. import java.util.Currency; //dollar format
  13. import java.util.Locale; //get defual location info (US)
  14. import java.text.NumberFormat; //numerical formating
  15.  
  16.  
  17. public class Assignment1d//4 reversions latter...
  18. {
  19. public static void main(String[] args)
  20. {
  21. displayMenu();//put the menu on screen
  22. /*choice out here so its scope can be used in conditional of while
  23.   the vaild user choice is passed to the local main var choice. this block
  24.   is here to make the program loop*/
  25. char choice = getMenuChoice();
  26. while(choice != 'Q')
  27. {
  28. /*when loanCaculator() is finished the menu is put back on screen
  29.   and the user can run the program again or pick Q to exit*/
  30. loanCaculator(choice);
  31. displayMenu();
  32. choice = getMenuChoice();
  33. }
  34. System.out.println("\nGood-bye\n");
  35. }
  36.  
  37. //displays the menu and prompt for menu choice
  38. //the method is void and accepts no parramaters
  39. public static void displayMenu()
  40. {
  41. System.out.println(" Loan Caluclator");
  42. System.out.println("**************************");
  43. System.out.println("P. Calulate monthly Payment");
  44. System.out.println("I. Calulate total Intrest");
  45. System.out.println("T. Calulate toatl Loan");
  46. System.out.println("Q. Exit program\n");
  47. System.out.print("Select P,I,T or Q: ");
  48. //no new line b/c sacnner input creats a newline.
  49. //do this so input is on the same line as the prompt
  50. }
  51.  
  52. /*this method gets the user menu choice thru scanner object.
  53.   the method returns a vaild char of P,I,T or Q to the main method in the form
  54.   of the char variable choice.*/
  55. public static char getMenuChoice()
  56. {
  57. //intialize new scanner object
  58. Scanner scanner = new Scanner(System.in);
  59.  
  60.  
  61. String stringInput = scanner.next();//get input as string
  62. //conver the above string into a single upper case char
  63. char charInput = Character.toUpperCase(stringInput.charAt(0));
  64.  
  65. /*error trapping
  66.   if charInput == Q then the while condition is false and the char 'Q' is
  67.   returned to main. Else then it is looped until a true statment is found.
  68.   when the ifs are true the char is returned to main. when none of the ifs
  69.   are true then the user has to renter a menu choice. this choice is then
  70.   tested running thru the while loop again untill a valid choice is given.
  71.   This way traps only good input and ingore all other input. is there a
  72.   better to hanndle this?
  73.   */
  74. while(charInput != 'Q')
  75. {
  76. if (charInput == 'P')
  77. return charInput;
  78. else if (charInput == 'I')
  79. return charInput;
  80. else if(charInput == 'T')
  81. return charInput;
  82. else
  83. {
  84. System.out.print("Select P,I,T or Q: ");
  85. stringInput = scanner.next();
  86. charInput = Character.toUpperCase(stringInput.charAt(0));
  87. }//else
  88. }//while loop
  89. return charInput;//return user input as upper case char
  90. }//end getMenuChoice
  91.  
  92.  
  93. /*This method accepts the user's VALID menue choice and asks for input for
  94.   amount, rate and term. note that all these vars are double b/c they under go
  95.   floating point opps. the method then uses a swtich statment to pick the right
  96.   method to call for calculation. the call statmetns in the switch print out
  97.   the value of the returned methods*/
  98. public static void loanCaculator(char choice)
  99. {
  100. //intialize new US currency format
  101. NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
  102.  
  103. //intialize new scanner object in here
  104. Scanner scanner = new Scanner(System.in);
  105.  
  106. System.out.print("Enter the principle of the loan: ");
  107. double amount = scanner.nextDouble();
  108.  
  109. //scope: rate must be out here to be used in while condition
  110. //do this to get rate inclusively between 1% to 100%
  111. double rate = 0.0;
  112. do
  113. {
  114. System.out.print("Enter the intrest rate between 1% and 100%: ");
  115. rate = scanner.nextDouble();
  116. }
  117. while(rate > 100.0 || rate < 1.0);
  118.  
  119. System.out.print("Enter the term of loan: ");
  120. double term =scanner.nextDouble();
  121.  
  122. System.out.print("The total cost is ");
  123.  
  124. //call the right method and return its value in local currancey format
  125. //new lines are added for output formating
  126. switch(choice)
  127. {
  128. case 'P':
  129. System.out.println(nf.format(calcPayment(amount, rate, term)) + "\n\n");
  130. break;
  131.  
  132. case 'I':
  133. System.out.println(nf.format(clacIntrest(amount, rate, term))+ "\n\n");
  134. break;
  135.  
  136. case 'T':
  137. System.out.println(nf.format(calcTotalLoan(amount, rate, term))+ "\n\n");
  138. break;
  139. }
  140. }
  141.  
  142. //these calc methods are not accurate to the real thing... takl to teacher...
  143. public static double calcPayment(double amount, double rate, double term)
  144. {
  145. return (amount * rate) / (1.0 - Math.pow((1.0 + rate), (-term)));
  146. }
  147.  
  148. public static double clacIntrest(double amount, double rate, double term)
  149. {
  150. return term * calcPayment(amount, rate, term) - amount;
  151. }
  152.  
  153. public static double calcTotalLoan(double amount, double rate, double term)
  154. {
  155. return amount + clacIntrest(amount, rate, term);
  156. }
  157.  
  158. }
__________________
i dont know much about programming but i try to help
mrynit is offline   Reply With Quote
Old Jan 22nd, 2007, 7:58 AM   #6
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
One key is to look at your logic carefully. You're hacking a path through the jungle over and over when your destination is always the same. Why not just,
public static char getMenuChoice()
{
    Scanner scanner = new Scanner(System.in);
    String stringInput;
    char cIn;    
    do
    {
        stringInput = scanner.next();
        cIn = Character.toUpperCase(stringInput.charAt(0));
        if ((cIn == 'P') || ((cIn == 'I') || ((cIn == 'L') || ((cIn == 'Q')) return cIn;
        System.out.print("Select P,I,T or Q: ");
    } while (true)
}
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Looping effect, when entering string in an int variable lamefif C++ 7 Jan 5th, 2006 11:29 AM
Endless looping >_< jch02140 C 13 Aug 4th, 2005 6:43 AM
looping in awk gwilliam Sed and Awk 3 Jun 20th, 2005 9:12 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 12:33 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC