尽管公共方法,变量不可用

时间:2014-01-31 16:55:50

标签: java android scope public

float targetVolume方法中创建的public void,但无法在其他public void方法中解析...

    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            float x = (float) Math.random();
            if (x < 0.5){
                float targetVolume = 0;
            } else {
                float targetVolume = 1;
            }

            scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    if (targetVolume.equals (1)){
                        mp.setVolume(startingVolume+volumeIncrement, startingVolume+volumeIncrement);
                    } else {
                        mp.setVolume(startingVolume-volumeIncrement, startingVolume-volumeIncrement);
                    }
                }
            }, 0, 1, TimeUnit.SECONDS);
        }
    }, 0, 5, TimeUnit.SECONDS);

我该如何解决这个问题?

编辑:我可以通过将最终修饰符添加到浮点数来解决问题:

        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            float x = (float) Math.random();
            final float targetVolume=(x < 0.5)?0:1;

            scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    if (targetVolume >startingVolume){
                        startingVolume = startingVolume+volumeIncrement;
                        mp.setVolume((startingVolume), (startingVolume));
                        }
                    else if (targetVolume < startingVolume){
                        startingVolume = startingVolume-volumeIncrement;
                        mp.setVolume((startingVolume), (startingVolume));
                        }              
                }
            }, 0, 1, TimeUnit.SECONDS);
        }
    }, 0, 5, TimeUnit.SECONDS);

但是,每次运行任务时,最终的float targetVolume现在是否保持相同的值(零或1)?我需要这个值随机改变......

2 个答案:

答案 0 :(得分:0)

您已在本地声明该方法

cheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
    public void run() {
        float x = (float) Math.random();
        if (x <0.5){
            float targetVolume =0;}

将其声明为类的成员变量以具有类范围。这意味着在方法之外的任何地方定义它(通常在onCreate()的{​​{1}}之前。

Read about Java variable scope

答案 1 :(得分:0)

更改为:

scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
    public void run() {
        float x = (float) Math.random();
        final float targetVolume=(x < 0.5)?0:1;

        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
            public void run() {
                if (targetVolume==1){
                    mp.setVolume(startingVolume+volumeIncrement, startingVolume+volumeIncrement);
                } else {
                    mp.setVolume(startingVolume-volumeIncrement, startingVolume-volumeIncrement);
                }
            }
        }, 0, 1, TimeUnit.SECONDS);
    }
}, 0, 5, TimeUnit.SECONDS);