Can a local variable be used out of a method?

前端 未结 3 546
广开言路
广开言路 2021-01-26 11:53

I\'ve got stuck in a problem about local variables.

The following is not my original code but I use a simple example to present my question:

import java.         


        
相关标签:
3条回答
  • 2021-01-26 12:05

    Why don't you just do this? :D Delcare the input1 outside the do...while loop, then it can be used in while statement.

    import java.util.Scanner;
        public static void main(String[] args) {
            Scanner userScan=new Scanner(System.in);  
            int input1 = 0;
            do{
                input1=userScan.nextInt();
            }while(input1>10);
        }
    
    0 讨论(0)
  • 2021-01-26 12:09
        public static void main(String[] args) 
       {
            Scanner userScan=new Scanner(System.in);    
            int input1;
            do{
                input1=userScan.nextInt();
            }while(input1>10);
        }
    

    just declare input1 outside of the scope of do while loop

    0 讨论(0)
  • 2021-01-26 12:17

    The problem is with your input1 variable scope i.e., the scope of your input1 variable is limited to do while block (i.e., { } code), so just declare the variable outside the loop.

    int input1 = 0;//scope is now wider, not just limited to the loop
    do {
       input1=userScan.nextInt();
    } while(input1>10);
    
    0 讨论(0)
提交回复
热议问题