Can a local variable be used out of a method?

前端 未结 3 573
广开言路
广开言路 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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);
    

提交回复
热议问题