gpt4 book ai didi

java - 无法访问在 try/catch 语句中初始化的变量

转载 作者:行者123 更新时间:2023-11-30 04:03:40 26 4
gpt4 key购买 nike

我正在为我的游戏制作一个声音类,经过多次尝试,我似乎无法摆脱 NullPointerException。发生这种情况是因为我无法访问 try/catch 语句中的变量。

这是代码:

package util;

import java.applet.*;
import java.net.URL;

public class Sound
{
private AudioClip audio;
private URL file;

public Sound(String srcfile)
{
try
{
this.file = new URL(srcfile);
}
catch(Exception e){}

this.audio = Applet.newAudioClip(file);
}

public void Play()
{
this.audio.play();
}

public void Loop()
{
this.audio.loop();
}

public void Stop()
{
this.audio.stop();
}

public AudioClip getAudio()
{
return audio;
}

public void setAudio(AudioClip audio)
{
this.audio = audio;
}
}

这是错误(不再出现):

Exception in thread "main" java.lang.NullPointerException
at sun.applet.AppletAudioClip.<init>(Unknown Source)
at java.applet.Applet.newAudioClip(Unknown Source)
at util.Sound.<init>(Sound.java:19)
at main.Blocks.run(Blocks.java:38)
at main.Blocks.main(Blocks.java:26)

修改旧代码后,她就是新代码:

package util;

import java.applet.*;
import java.net.URL;

public class Sound
{
private AudioClip audio;

public Sound(String srcfile)
{
try
{
this.audio = Applet.newAudioClip(new URL("file://" + srcfile));
}
catch(Exception e)
{
Log.log(e.getMessage(), Log.ERROR);
e.printStackTrace();
System.exit(1);
}
}

public void Play()
{
this.audio.play();
}

public void Loop()
{
this.audio.loop();
}

public void Stop()
{
this.audio.stop();
}

public AudioClip getAudio()
{
return audio;
}

public void setAudio(AudioClip audio)
{
this.audio = audio;
}
}

我正在打电话 玩();但什么也没发生

这是我调用该方法的方式:

Sound snd = new Sound("res/dev/sound.wav");
snd.Play();

如有任何帮助,我们将不胜感激。

最佳答案

从类的设计方式来看,似乎不需要 file 变量存在于构造函数之外。像这样的东西可能会很好用:

public Sound(String srcfile) {
try {
this.audio = Applet.newAudioClip(new URL(srcfile));
}
catch(Exception e){
//at least print the stack trace
e.printStackTrace();
//do some proper exception handling that makes sense for you app!
}
}

关于java - 无法访问在 try/catch 语句中初始化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21321633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com