如何使用printwriter连接不同的方法?

时间:2019-03-06 21:32:05

标签: java

我执行了以下方法。 findSum有效,而factorialhowmanyeven不起作用。

我的方法是否错误,或者主程序中缺少某些内容?

findSum

import java.io.*;
import java.util.Scanner;
public class Sum{
public static int findSum(int a,int b,int c,PrintWriter output){
  int max=0;
  if (a>b && b<c){
    max=a+c;
  }if (a>b && b>c){
    max=a+b;
  }if (a<b && b<c){
    max=c+b;
  }
 return max;
}

阶乘

public static int factorial(int n,PrintWriter output){
  int max=1;
  for (int p=2;p<=n;p++){
    max*=p;
  }
  if (n>0){
    output.println(max+"! is "+n);
  }else{
    output.println("it is not possible to calculate the factorial");
  }
  return max;
}

howmanyeven

public static int howmanyeven(int z,PrintWriter output){
  int max=z;
    while (z%2==0){
      output.println("There is/are "+z+" even number(s)");
      output.close();
    }
  return max;
}

主程序

public static void main(String[]args)throws FileNotFoundException{
  Scanner input =new Scanner(System.in);
  System.out.println("Enter VAL. -1 to end:");
  int val,a,b,c,count=0;
  val=input.nextInt();
  PrintWriter output=new PrintWriter("Sum.txt");
  while (val!=-1){
    System.out.println("Enter a,b,c:");
    a=input.nextInt();
    b=input.nextInt();
    c=input.nextInt();
    int max;
    max=findSum(a,b,c,output);
    output.println("The three original integers are "+a+" "+b+" "+c+" \n"+max+" is the sum\n");
    System.out.println("Enter VAL. -1 to end:");
    val=input.nextInt();
    count++;
  }
  output.println(count+" sets of three data were entered and processed");
  output.close();
  input.close();
  }
}

1 个答案:

答案 0 :(得分:1)

您可以调用其他类似的方法,并且不要在方法中使用PrintWriter,仅保留用于执行操作的方法而不使用结果

public static int factorial(int n){
    int max = 1;
    for (int p=2; p<=n ; p++){
        max *= p;
    }
    return max;
}

public static List<Integer> howmanyeven(int... values){
    List<Integer> res = new ArrayList<>();
    for(int i=0; i<values.length; i++){
        if(values[i]%2 == 0){
            res.add(values[i]);
        }
    } 
    return res;
}

max = findSum(a, b, c);
output.println("The three original integers are "+a+" "+b+" "+c+" \n" max+" is the sum\n");

int facto = factorial(max)
output.println("Factorial of "+ max + "is" + facto);

List<Integer> even = howmanyeven(a,b,c)
output.println("The evens are "   + even)