Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3. public class Uin8468hw3 {
  4. Scanner in = new Scanner(System.in);
  5. int numIter = 0;
  6. int choice = 0;
  7. int x = 0;
  8. int total = 0;
  9. String awesomeString = new String();
  10. FileWriter fstream;
  11. BufferedWriter out;
  12.  
  13. public Uin8468hw3(){
  14. try{
  15. fstream = new FileWriter("outfile.txt");
  16. out = new BufferedWriter(fstream);
  17. }catch(Exception e){
  18. System.err.println("Error: " + e.getMessage());
  19. }
  20.  
  21. System.out.print("Please enter number of iterations (integer larger than 0): ");
  22. numIter = in.nextInt();
  23.  
  24. if (numIter > 0){
  25. for (int i = 0; i < numIter; i++){
  26. System.out.println("Please enter a choice (1 or 2) followed by a positive integer for x:");
  27. choice = in.nextInt();
  28. x = in.nextInt();
  29.  
  30. if (choice == 1){
  31. System.out.println("" + factorial(x));
  32. awesomeString = "" + factorial(x) + "\n";
  33. try{
  34. out.write(awesomeString);
  35. }catch(Exception e){
  36. System.err.println("Error: " + e.getMessage());
  37. }
  38. total = 0;
  39. }else if (choice == 2){
  40. System.out.println("" + sum(x));
  41. awesomeString = "" + sum(x) + "\n";
  42. try{
  43. out.write(awesomeString);
  44. }catch(Exception e){
  45. System.err.println("Error: " + e.getMessage());
  46. }
  47. total = 0;
  48. }else{
  49. if (x < 0){
  50. System.out.print("Number " + numIter + " is less than 1. ");
  51. }else{
  52. System.out.print("Number " + numIter + "is not a valid choice. ");
  53. }
  54. }
  55. }
  56. try{
  57. out.close();
  58. }catch(Exception e){
  59. System.err.println("Error: " + e.getMessage());
  60. }
  61. }else{
  62. System.out.println("Please rerun the program entering an integer larger than 0.");
  63. }
  64. }
  65.  
  66. public int factorial(int p){
  67. total = 1;
  68. for (int j = 1; j <= p; j++){
  69. total *= j;
  70. }
  71. return total;
  72. }
  73.  
  74. public int sum(int q){
  75. for (int k = 1; k <= q; k++){
  76. total += k;
  77. }
  78. return total;
  79. }
  80.  
  81. public static void main(String[] args) {
  82. Uin8468hw3 a = new Uin8468hw3();
  83. }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement