[英]Variable cannot be resolved in an If-Statement
我正在嘗試做以下教程問題。
// Create a method called greatestCommonFactor
// It should return the greatest common factor
// between two numbers.
//
// Examples of greatestCommonFactor:
// greatestCommonFactor(6, 4) // returns 2
// greatestCommonFactor(7, 9) // returns 1
// greatestCommonFactor(20, 30) // returns 10
//
// Hint: start a counter from 1 and try to divide both
// numbers by the counter. If the remainder of both divisions
// is 0, then the counter is a common factor. Continue incrementing
// the counter to find the greatest common factor. Use a while loop
// to increment the counter.
我的代碼如下
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Ex4_GreatestCommonFactor {
// This is the main method that is executed as
// soon as the program starts.
public static void main(String[] args) {
// Call the greatestCommonFactor method a few times and print the results
}
public static int greatestCommonFactor(int a, int b){
int i = 1 ;
while (i >= 1 ){
i++;
}
if (a%i == 0 && b%i == 0){
ArrayList factor = new ArrayList<Integer>();
factor.add(i);
}
else if (a%i <= 1 || b%i <= 1){
Collections.sort(factor);
List<Integer> topnum = factor.subList(factor.size() - 1, factor.size());
}
return topnum;
}
}
所以我有兩個問題。
1)在我的elseif語句中,出現錯誤,無法將factor
解析為變量。 如何將前一個If語句中的ArrayList factor
“繼承”到此elseif語句中?
2)我也收到類似的錯誤,其中topnum
無法解決。 這是否也是我方法中這一行代碼的放置錯誤,還是我犯了一個完全不同的錯誤?
1)在我的elseif語句中,出現錯誤,無法將因子解析為變量。 如何將前一個If語句中的ArrayList因子“繼承”到此elseif語句中?
通過在之前聲明它
ArrayList factor = null;
if ( /* some condition */ ) {
// initialize factor
} else if (/* some condition */) {
// access factor here
}
每個變量(在Java的其他“部分”中)都有一個范圍,在該范圍內可用。 作用域通常是在其中聲明變量的塊。
阻止: http : //docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
在您的方法greatCommonFactor中,存在三個變量,它們在整個方法中均有效:a,b,i
從方法的開始(第一個打開的大括號)到方法的結尾(最后一個關閉的大括號),您可以在任何地方訪問它們。
您的第一個if語句中的塊是新作用域。 在程序執行離開此塊后,在此范圍內聲明factor並將不再可用。
if (a%i == 0 && b%i == 0){ // Start of Block/Scope
ArrayList factor = new ArrayList<Integer>(); // Declaration, you can access factor now
factor.add(i);
} // End of Block/Scope, factor inaccessible
else if部分是一個具有自己作用域的新塊。
else if (a%i <= 1 || b%i <= 1){
Collections.sort(factor);
List<Integer> topnum = factor.subList(factor.size() - 1, factor.size());
}
在第一個塊中聲明的因數不再存在。 您可以拉起聲明並將其放在if之外。
public static int greatestCommonFactor(int a, int b){
int i = 1 ;
while (i >= 1 ){
i++;
}
ArrayList<Integer> factor = new ArrayList<Integer>();
if (a%i == 0 && b%i == 0){
factor.add(i);
}
else if (a%i <= 1 || b%i <= 1){
Collections.sort(factor);
List<Integer> topnum = factor.subList(factor.size() - 1, factor.size());
}
return topnum;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.