Java 如何打印选项b系列的总和

Java 如何打印选项b系列的总和,java,switch-statement,series,Java,Switch Statement,Series,我是这个网站的新手,我可能问错了问题,请原谅 我已经完成了选项a,但对于选项b的总和,我无法得到期望的结果 我可以打印序列,但不能打印总和2-5+10-17+26-37+…。最多n个术语 import java.util.*; class menu { public static void main(String args[]) { String choice=""; Scanner sc=new Scanner(System.

我是这个网站的新手,我可能问错了问题,请原谅

我已经完成了选项a,但对于选项b的总和,我无法得到期望的结果 我可以打印序列,但不能打印总和2-5+10-17+26-37+…。最多n个术语

import java.util.*;
class menu
{
    public static void main(String args[])
    {
        String choice="";
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter your choice 'a' or 'b'");
        choice=sc.nextLine();
        switch(choice)
        {
            case "a":
            int i,j;
            for ( i=1; i <=5; i++)
            {
                for (j=5; j >=i; j--)
                {
                    if ((i + j) % 2 == 0) {
                        System.out.print("1 ");
                    } 
                    else 
                    {
                        System.out.print("0 ");
                    }
                }
                System.out.println();
            }
            break;
            case "b":
            System.out.println("Enter 'n' th term"); 
            int sum=0,f,s,into,n;
            n=sc.nextInt();
            for(f=1;f<=n;f++)
            {
                s=(f*f+1);
                sum+=s;
                
                
            }
            System.out.print(sum);
            break;
            default:
            System.out.println("Wrong Choice");
        }
    }
}
import java.util.*;
班级菜单
{
公共静态void main(字符串参数[])
{
字符串选择=”;
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入您的选择‘a’或‘b’”);
choice=sc.nextLine();
开关(选择)
{
案例“a”:
int i,j;
对于(i=1;i=i;j--)
{
如果((i+j)%2==0){
系统输出打印(“1”);
} 
其他的
{
系统输出打印(“0”);
}
}
System.out.println();
}
打破
案例“b”:
System.out.println(“输入第n个术语”);
int sum=0,f,s,in,n;
n=sc.nextInt();

对于(f=1;f保留一个在1和-1之间翻转的
sgn
变量。 将每个术语乘以
sgn
,然后将其相加,然后翻转
sgn
为下一个术语做好准备:

int sgn = 1; 
for(f=1;f<=n;f++)
{
    s=sgn*(f*f+1);
    sum+=s;
    sgn *= -1;
}
intsgn=1;

对于(f=1;f以
2
开始术语,然后处理剩余但最后一个术语,以便您可以在除最后一个术语之外的所有术语之后打印适当的符号(即
+/-
)。请注意,您还需要使用正确的符号将每个术语添加到
和中

System.out.println("Enter number of terms: ");
int sum = 0, f, n, term;
n = sc.nextInt();

// Start term with 2
term = 2;

// Process the remaining but the last term
for (f = 2; f <= n; f++) {
    System.out.print(term + (f % 2 == 0 ? " - " : " + "));
    sum += f % 2 == 0 ? term : -term;
    term = term + (2 * f - 1);
}

// Process the last term
System.out.println(term);
sum += f % 2 == 0 ? term : -term;

// Display sum
System.out.print(sum);

如果你能打印序列,是什么阻止你打印序列的和?我不能做+-交替和
Enter your choice 'a' or 'b'
b
Enter number of terms: 
5
2 - 5 + 10 - 17 + 26
16