简体   繁体   中英

unable to access variable outside the while loop in java

In this code I am trying to find maximum of n numbers. 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. You need to provide an exit condition from that loop or else System.out.println(maximum) can never be reached.

This is the solution i found for the code.

public 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);

        for(int i =0 ; i < n; i++){

            if(maximum < leastNum[i]){
                maximum = leastNum[i];
            }
        }
        System.out.println(maximum);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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