繁体   English   中英

无法访问 java 中的 while 循环外的变量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM