简体   繁体   中英

Want to access variable outside the loop

I want to print all those number which is taken by input and print but problem is that the variable which is inside the loop can not be accessed outside of the loop. Why it is so .

import java.util.*;

public class Solution {
public static void main(String[] args) {
  Scanner Sc = new Scanner(System.in);
  for(int i=0;i<3;i++){
      int a = Sc.nextInt();
      
  }
 System.out.println(a);
}

}

Showing error " System.out.println(a); ^ symbol: variable a location: class Solution 1 error "

My Input is :
1
2
3

Desired output

1
2
3

You can use arrays for this problem. Since you don't prompt the user about how many inputs the user will give, I've added a final int ARRAY_SIZE variable to declare the number of inputs the user can give.

I placed another for loop that will iterate over the array for printing.

import java.util.*;

class Solution {
    public static void main(String[] args) {
        final int ARRAY_SIZE = 3;
        Scanner Sc = new Scanner(System.in);
        int[] a = new int[ARRAY_SIZE];

        for (int i = 0; i < ARRAY_SIZE; i++) {
            a[i] = Sc.nextInt();
        }

        for (int i = 0; i < ARRAY_SIZE; i++) {
            System.out.println(a[i]);
        }
        
    }
}

Input:

1
2
3

Output:

1
2
3

Some Notes:

  1. The convention of naming objects in Java should be in lowerCamelCase, meaning your Scanner Sc should instead be named Scanner sc .
  2. Java has scopes of variables that differ on where they were declared, you can read more in https://www.javatpoint.com/scope-of-variables-in-java

The variable which you are using in the for loop is only limited inside it.You cannot access that variable outside because it is a local variable and not an instance variable.I don't know what kind of output is needed but here's something which might help.

Scanner sc=new Scanner(System.in);
    System.out.println("How many numbers do u want to enter???");
    int totalNumbers=sc.nextInt();
    System.out.println("Enter numbers");
    while(totalNumbers>0) {
        int a=sc.nextInt();
        System.out.println(a);
        totalNumbers--;
    }

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