Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Scanner;
- public class Uin8468hw3 {
- Scanner in = new Scanner(System.in);
- int numIter = 0;
- int choice = 0;
- int x = 0;
- int total = 0;
- String awesomeString = new String();
- FileWriter fstream;
- BufferedWriter out;
- public Uin8468hw3(){
- try{
- fstream = new FileWriter("outfile.txt");
- out = new BufferedWriter(fstream);
- }catch(Exception e){
- System.err.println("Error: " + e.getMessage());
- }
- System.out.print("Please enter number of iterations (integer larger than 0): ");
- numIter = in.nextInt();
- if (numIter > 0){
- for (int i = 0; i < numIter; i++){
- System.out.println("Please enter a choice (1 or 2) followed by a positive integer for x:");
- choice = in.nextInt();
- x = in.nextInt();
- if (choice == 1){
- System.out.println("" + factorial(x));
- awesomeString = "" + factorial(x) + "\n";
- try{
- out.write(awesomeString);
- }catch(Exception e){
- System.err.println("Error: " + e.getMessage());
- }
- total = 0;
- }else if (choice == 2){
- System.out.println("" + sum(x));
- awesomeString = "" + sum(x) + "\n";
- try{
- out.write(awesomeString);
- }catch(Exception e){
- System.err.println("Error: " + e.getMessage());
- }
- total = 0;
- }else{
- if (x < 0){
- System.out.print("Number " + numIter + " is less than 1. ");
- }else{
- System.out.print("Number " + numIter + "is not a valid choice. ");
- }
- }
- }
- try{
- out.close();
- }catch(Exception e){
- System.err.println("Error: " + e.getMessage());
- }
- }else{
- System.out.println("Please rerun the program entering an integer larger than 0.");
- }
- }
- public int factorial(int p){
- total = 1;
- for (int j = 1; j <= p; j++){
- total *= j;
- }
- return total;
- }
- public int sum(int q){
- for (int k = 1; k <= q; k++){
- total += k;
- }
- return total;
- }
- public static void main(String[] args) {
- Uin8468hw3 a = new Uin8468hw3();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement