gpt4 book ai didi

java - 如何使用 printwriter 连接单独的方法?

转载 作者:行者123 更新时间:2023-12-02 10:10:27 24 4
gpt4 key购买 nike

我执行了以下方法。 findSum 有效,而 factorialhowmanyeven 无效。

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

求和

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;
}

多少甚至

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();
}
}

最佳答案

你可以像这样调用其他方法,并且不要在方法中使用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)

关于java - 如何使用 printwriter 连接单独的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55032482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com