我已经实现了类似于简单时钟的代码,每次在我的班级中它应该增加1。到目前为止,这是我在主程序中的内容:
for (key, value) in parameters {
var dataToAppend: Data?
if let data = value as? Data {
dataToAppend = data
} else if let v = value as? String, let valueAsData = v.data(using: .utf8) {
dataToAppend = valueAsData
}
if let d = dataToAppend {
multipartFormData.append(d, withName: key )
}
}
这里是班级" BoundedCounter" :
public static void main(String[] args) {
BoundedCounter counter = new BoundedCounter(60);
System.out.println("Value at start: " + counter);
int i = 0;
while (i < 10) {
counter.next();
System.out.println("Value: " + counter);
i++;
}
}
此代码的输出为:
class BoundedCounter {
private int value;
private int upperBound;
public BoundedCounter(int upperBound) {
this.upperBound = upperBound;
this.value = 0;
}
public void next () {
if (value++ > upperBound) {
value = 0;
} else {
value++;
}
}
public String toString() {
return "" + value;
}
}
我不明白为什么它会增加2,而在课堂上,while语句有Value at start: 0
Value: 2
Value: 4
Value: 6
Value: 8
Value: 10
Value: 12
Value: 14
Value: 16
Value: 18
Value: 20
;这意味着它应该增加1.
我在这里缺少什么?
答案 0 :(得分:11)
您的if
执行value++
然后(假设输入了else
)您再次执行此操作。变化
if (value++ > upperBound) {
value = 0;
} else {
value++;
}
类似
if (value + 1 > upperBound) {
value = 0;
} else {
value++;
}
或强>
if (value < upperBound) {
value++;
} else {
value = 0;
}