可以在方法中使用局部变量吗? [英] Can a local variable be used out of a method?

查看:125
本文介绍了可以在方法中使用局部变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了关于局部变量的问题。

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.util.Scanner;
public static void main(String[] args) {
    Scanner userScan=new Scanner(System.in);    
    do{
        int input1=userScan.nextInt();
    }while(input1>10);
}

我的目的是让用户输入一个我想要的整数范围。
如果键入的数字不符合规则,我希望用户可以再次键入,直到它为止。但是,input1是局部变量,因此在while的表达式中无效。但我不希望用户再次重新输入整数。仅使用一个变量会更好。有没有人有关于它的建议或其他可以实现这个想法的方法?
谢谢!

My purpose is to let a user type in an integer which is in my intended range. If the typed number does not meet the rule, I hope the user can type again until it does. However, the "input1" is a local variable, so it will not be valid in the expression of while. But I do not want the user to re-type the integer again. Using only one variable would be better. Does anyone have advices about it or other ways which can implement this idea? Thank you!

推荐答案

    public static void main(String[] args) 
   {
        Scanner userScan=new Scanner(System.in);    
        int input1;
        do{
            input1=userScan.nextInt();
        }while(input1>10);
    }

只是在do while循环范围之外声明input1

just declare input1 outside of the scope of do while loop

这篇关于可以在方法中使用局部变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆