java - 如何以 (System.out.println(numbers)); 打印的方式将数字相加数字++;

标签 java math sum addition

我如何以与打印数字相同的方式将数字加在一起。

    System.out.println(numbers);
    numbers++;

这会像这样打印。

    1
    2
    3
    4

等等

如何将它们加在一起为 1+2+3+4

这是我当前关于这个问题的代码。 这是我在赫尔辛基大学的 MOOC 中进行的练习,我住在美国,因此由于 8 小时的时差,很难寻求帮助。

    public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.print("Until What?:");
    // the user inputs a number here
    int blockExe = 1;
    // the blockExe variable is supposed to store a count of how many times the
    // block has been executed which i belive should be limited to the user input
    int userIn = Integer.parseInt(reader.nextLine());
    int sum = userIn + blockExe;
    // i am supposed to add the number of block executions the user input 
    // each time adding 1 to the execution so 1+2+3
    // then printing the sum of those numbers

    while (blockExe <= userIn) {
        blockExe += 1;
        if (blockExe + userIn == sum) {
            break;
        }
    }
    System.out.println("Sum is:" +sum);

}

}

最佳答案

此代码不明确:

while (blockExe <= userIn) {
    blockExe += 1;
    if (blockExe + userIn == sum) {
        break;
    }
}

也许你想要这个:

int sum=0;
for(blockExe = 1;blockExe <= userIn; blockExe ++) {
    sum+=blockExe;
}

关于java - 如何以 (System.out.println(numbers)); 打印的方式将数字相加数字++;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23306164/

相关文章:

java - 将应用程序安装到 Tomcat7 中以与 sonarqube 4.1 一起运行(maven 插件)

java - Spring Security LDAP 身份验证并从本地数据库收集用户详细信息

javascript - JavaScript 中更好的随机函数

php - 在一个查询中插入多行求和

python - 如何将 Pandas 中的数据帧相加超过 5 个

Java max文件缓存解决方案

java - 我可以在 JBoss 应用程序服务器上部署 java 应用程序和 php 应用程序吗?

algorithm - 概率:如果你有 n 个骰子,每个骰子都有 m 个面,则没有获胜的方法

c++ - 计算二维 vector 的偏航

r - 计算 R 中矩阵行的总和