如何将数字添加到一起,就像我打印它们一样。
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);
}
}
答案 0 :(得分:1)
此代码含糊不清:
while (blockExe <= userIn) {
blockExe += 1;
if (blockExe + userIn == sum) {
break;
}
}
也许你想要这个:
int sum=0;
for(blockExe = 1;blockExe <= userIn; blockExe ++) {
sum+=blockExe;
}
答案 1 :(得分:0)
System.out.println(“Sum is:”+ sum);
这条线没有意义。我认为你想要输出的数字应该是blockExe但是你不清楚你要从你的描述做什么。尝试将该行更改为:
System.out.println(“Sum is:”blockExe);
并查看是否能让您更接近答案。