类我在理解这个Java如何与我提供给它的参数一起工作时遇到问题
我遇到的问题是在运行命令时理解以下代码: java驱动程序1000000 它的回归: 总和(1000000)=1784293664
不管我花多长时间去看它,我都不明白为什么代码会这样做,我只是想知道是否有人能帮我理解代码对数字的实际作用
class Sum
{
private int sum;
public int get() {
return sum;
}
public void set(int sum) {
this.sum = sum;
}
}
class Summation implements Runnable
{
private int upper;
private Sum sumValue;
public Summation(int upper, Sum sumValue) {
this.upper = upper;
this.sumValue = sumValue;
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++)
sum += i;
sumValue.set(sum);
}
}
public class Driver
{
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage Driver <integer>");
System.exit(0);
}
if (Integer.parseInt(args[0]) < 0) {
System.err.println(args[0] + " must be >= 0");
System.exit(0);
}
// Create the shared object
Sum sumObject = new Sum();
int upper = Integer.parseInt(args[0]);
Thread worker = new Thread(new Summation(upper, sumObject));
worker.start();
try {
worker.join();
} catch (InterruptedException ie) { }
System.out.println("sum(" + upper + ") = " + sumObject.get());
}
}
提前谢谢
安德鲁
# 1 楼答案
将1到100万的数字相加:
这会导致用于保存总和的
int
溢出。结果是:使用} 并且可以保存总和
long
存储总和;它有一个maximum value of ^{