[英]unable to access variable outside the while loop in java
在這段代碼中,我試圖找到最多 n 個數字。 我已經聲明了最大外部循環,但以后無法訪問最大變量:
public class MaxOfNnumbers {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader (System.in));
int maximum = Integer.parseInt(reader.readLine ());
//write your code here
while(true) {
String s = reader.readLine ();
int n = Integer.parseInt ( s );
if (n > 0) {
if (n > maximum) {
n = maximum;
}
}
}
System.out.println ( maximum );// Error indicates that , maximum variable is unreachable
}
}
代碼中的while(true)
行設置了一個無限循環。 您需要從該循環中提供退出條件,否則永遠無法達到System.out.println(maximum)
。
這是我為代碼找到的解決方案。
公共 class MaxOfNnumbers {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader (System.in));
System.out.println ("Enter the amount of numbers to be scanned");
// if we enter n to be 0 or negative , we cant form an array
// hence an if condition where if(n > 0) is applied before forming
// the array .
int n = Integer.parseInt ( reader.readLine () );
System.out.println ( "Entered value for n is "+n );
int leastNum[] = new int[n];
System.out.println ("Array size is "+leastNum);
// for reading the data from keyboard least num array is declared
// this array is fed from the keyboard .
if(n > 0){
for(int i = 0; i < n ; i++){
leastNum[i]=Integer.parseInt ( reader.readLine () );
System.out.println ("Value stored at "+ i+ "Location is"+leastNum[i]);
}
System.out.println ("Least num length is "+leastNum.length);
int maximum = Integer.MIN_VALUE;
System.out.println("最大值的初始值為"+maximum);
for(int i =0 ; i < n; i++){
if(maximum < leastNum[i]){
maximum = leastNum[i];
}
}
System.out.println(maximum);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.