java奇数行输出n个_java – 如何添加’n’个奇数?

我正在尝试编写一个计算前n个正奇数整数之和的程序.

我无法弄清楚如何将n合并到求和中.我已经有一个do / while循环来确保在赋值时得到正值.我知道我必须使用for循环,但我不确定我会怎么做.

Scanner input = new Scanner(System.in); // open input stream

String cleanUpStr; // clean kbd buffer

int n; // number

int sum; // sum of numbers

int cntr; // counter for loop

cleanUpStr = "nothing yet";

n = 0;

sum = 0;

cntr = 0;

//prompt user for the value of n

// use a loop to ensure a positive output

do

{

System.out.println("Enter the value of n");

n = input.nextInt();

cleanUpStr = input.nextLine();

// print error if n is invalid

if (n < 0)

{

System.out.println("Invalid n value of " + n + ", try again.");

} // end if

}while(n < 0);

for(cntr = 0; cntr < n; ++cntr)

{

} // end for

} // end main

例如:如果n = 5,那么这应该计算1 3 5 7 9.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值