Can a local variable be used out of a method?

你。 提交于 2019-12-02 10:56:13
    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

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!