简体   繁体   中英

Why am I not able to print the value outside th e for loop

I am trying to print the value of max but not able to print. But once I put the Print statement inside the for loop then I can print it. Can anyone please help me out

class Codechef {
     public static void main(String[] args) throws java.lang.Exception {
        // your code goes here
        try {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = sc.nextInt();

            }
            int max = a[0];

            for (int i = 0; i < n; i++) {
                int sum = a[i];
                while (a[i + 1] > a[i] && i + 1 < n) {

                    sum = sum + a[i + 1];
                    i++;
                }
                if (sum > max) {
                    max = sum;

                }


            }
            System.out.println(max);


        } catch (Exception e) {
            return;
        }
    }
}

As pointed out in comments, you should add e.printStackTrace() to check what exception is being thrown.

        } catch (Exception e) {
            e.printStackTrace();
        }

When I added it in your catch block, I was able to see underlying problem:

5
1 2 3 4 5
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at in.rohaan.PrintMaxValue.main(PrintMaxValue.java:19)

Problem seemed to be inside inner while loop where you were accessing array element first before checking whether index is valid or not. You were doing this:

while(a[i+1] > a[i] && i+1<n){ // Would fail for i=n-1 

It should actually be:

while (i + 1 < n && a[i + 1] > a[i]) { // ((n-1) + 1 < n) returns false, statement is not executed

When I updated while 's condition, I was able to see max being printed:

5
1 2 3 4 5
15

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