Home > Software engineering >  How to access inner array in out side of nestes for loop
How to access inner array in out side of nestes for loop

Time:02-08

I want make code in which we have to add inputs and it show output at very after all inputs are performed. But i don't know how can i access the contents of variable in for loop in outer side.

My code is given below

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {
      
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        for(int i=0;i<T;i  )
        {
            int N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j  )
            {
                int C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][]A =new int[T][N];

        //I know here No issue with T but how can i acces N and C?

        //here code to show output of given inputs.....
....
..


    }
}

Ex:-

Input:--

2 //test cases

3  //items

1  2  3  //costs

4  //items

1 2 3 4  //costs


Ouput:---perfectly as in input.

CodePudding user response:

If I right understand what do you want, you should declare N and C at procedure begin:

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {
      
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        int N=0;
        int C=0;
        for(int i=0;i<T;i  )
        {
            N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j  )
            {
                C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][][]A =new int[T][N][C];

        //Now here T,N and C are accessible

        //here code to show output of given inputs.....
....
..


    }
}

CodePudding user response:

I don't understand the question, but in any case your variables (except T) are out of scope. Should be something like (psueo-code)

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {
      
        int [][][] A;
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case? say 3
        for(int i=0;i<T;i  )
        {
            int N=sc.nextInt();        //How many items in each cases? say 14
            for(int j=0;j<N;j  )
            {
                int C=sc.nextInt();   //How much cost of each items? say 2
                A =new int[T][N][C]; // ok, you got a 3x14X2 array
                // now do here or outside what you want with it
            }
        }
        
        //I know here No issue with T but how can i acces N and C?
        // you can use A 3 dimensional array  here

        //here code to show output of given inputs.....
....
..


    }
}
  •  Tags:  
  • Related