gpt4 book ai didi

java - 将for循环输入的数字相加

转载 作者:行者123 更新时间:2023-12-01 15:16:39 28 4
gpt4 key购买 nike

我的目标是使用 for 循环添加用户输入的数字。

这是我的代码:

import java.io.*;
class Student {
public static void main (String args[]){
int mks=0, i=0 ,percnt=0;
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
try {
System.out.println("Enter Marks Of Student ");

for (i=0;i<=4;i++){
mks= Integer.parseInt(br.readLine());
mks=mks+i;
}
}catch (Exception e) {}
percnt=mks/5;

System.out.println("GRAND TOTAL = "+mks+ " PERCENTAGE"+percnt);
}
}

我使用此代码获取了最后输入的分数 + 4。

最佳答案

"my objective is to add the numbers entered by the user using for loop"

您需要累积用户输入的每个整数:

mks += Integer.parseInt(br.readLine());

"i m getting marks entered last + 4 with this code"

这是因为您的代码:

mks= Integer.parseInt(br.readLine());  // Get the integer the user entered
mks=mks+i; // Add i (which in the case of the last iteration is 4)

每次循环重新启动时都会设置mks的值。此外,如果您尝试计算用户输入的所有数字,则无需将循环计数器 i 添加到累加器变量 mks

关于java - 将for循环输入的数字相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11513139/

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