[英]How do I implement a reset for my loop counter?
我有一個動作監聽器,它調用一些方法,其中一個方法計算另一個方法運行循環的次數。 我遇到的問題是計數器只是增加了自己(我明白為什么我只是不知道如何修復它)而不是重置為0。
這是我的動作監聽器代碼。
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
調用方法並設置文本的ActionListener:
public void actionPerformed(ActionEvent e) {
int n = Integer.parseInt(nField.getText());
//Try Catch for Iterate Radio Button
if (iterateBtn.isSelected()){
try {
double result = sequence.computeIterative(n);
int efficiency = sequence.getEfficiency();
rField.setText(Double.toString(result));
eField.setText(Integer.toString(efficiency));
}
catch (InvalidInput ex) {
}
}
getEfficiency方法計算computeIterative方法中的循環運行次數,然后將其設置為textField。
這是我的getEfficiency方法:
public int getEfficiency() {
efficiency++;
return efficiency;
}
現在顯然這將繼續增加自己,我相信我看起來太難以找到解決方案,但我無法弄明白。
基本上,在try,catch之后,我需要將效率設置為0,以便下次調用computeIterative(n)方法時,我得到一個正確的讀數。
您只需添加方法resetEfficiency()
:
public int resetEfficiency() {
efficiency = 0;
}
然后在computeIterative()
的開頭調用它:
public double computeIterative(double n) throws InvalidInput {
this.resetEfficiency();
//rest of code goes here
//....
}
(當然我假設這不是多線程或任何東西)。
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
this.resetEfficiencyCounter(); //Call Reset if Number Got Invalid.
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
添加新函數命名為resetEfficiencyCounter()
。
private void resetEfficiencyCounter(){
this.efficiency = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.