[英]unable to access variable outside the while loop in java
In this code I am trying to find maximum of n numbers.在这段代码中,我试图找到最多 n 个数字。 I have declared maximum outside loop, but unable to access the maximum variable later:
我已经声明了最大外部循环,但以后无法访问最大变量:
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
}
}
The while(true)
line in your code sets up an infinite loop.代码中的
while(true)
行设置了一个无限循环。 You need to provide an exit condition from that loop or else System.out.println(maximum)
can never be reached.您需要从该循环中提供退出条件,否则永远无法达到
System.out.println(maximum)
。
This is the solution i found for the code.
这是我为代码找到的解决方案。
public class MaxOfNnumbers {公共 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 ("intial value of maximum is "+maximum); 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.