简体   繁体   English

想访问循环外的变量

[英]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 "显示错误“System.out.println(a); ^ symbol: variable a location: class Solution 1 error”

My Input is :
1
2
3

Desired output所需 output

1
2
3

You can use arrays for this problem.您可以使用 arrays 解决此问题。 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.由于您不提示用户用户将提供多少输入,因此我添加了一个final int ARRAY_SIZE变量来声明用户可以提供的输入数量。

I placed another for loop that will iterate over the array for printing.我放置了另一个for循环,它将遍历数组以进行打印。

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: 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 . Java 中命名对象的约定应采用小驼峰形式,这意味着您的Scanner Sc应改为命名为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 Java 的变量范围因声明位置而异,您可以在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.您在 for 循环中使用的变量仅限于它内部。您无法在外部访问该变量,因为它是局部变量而不是实例变量。我不知道需要哪种 output 但这里有一些可能帮助。

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--;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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