以下是一些功能:
jTextField1.setEnabled(false);
jTextField2.setEnabled(false);
jTextField3.setEnabled(false);
jComboBox1.setEnabled(false);
jComboBox2.setEnabled(false);
String samplingRate = jTextField1.getText();
String sampleSize = jTextField2.getText();
String channels = jTextField3.getText();
String endian = (String)jComboBox1.getSelectedItem();
String outputFormat = (String)jComboBox2.getSelectedItem();
AudioFormat outputAudioFormat = new AudioFormat( Float.parseFloat(samplingRate) , Integer.parseInt(sampleSize) , Integer.parseInt(channels) , true , Boolean.parseBoolean(endian) );
AudioInputStream newAIS; // newAIS declared Here
try {
newAIS = AudioSystem.getAudioInputStream(outputAudioFormat, AudioSystem.getAudioInputStream(new File(originalFile) ) );
// The above statement converts the data in the original file to the data filled by the user
} catch( Exception exc ){
System.out.println( exc );
}
String outLoc = null;
JFileChooser saveLoc = new JFileChooser();
int option = saveLoc.showSaveDialog(this);
if( option == JFileChooser.APPROVE_OPTION )
outLoc = saveLoc.getSelectedFile().getAbsolutePath();
try {
if( outputFormat == "AIFF" ) {
AudioSystem.write(newAIS, AudioFileFormat.Type.AIFF, new File(outLoc) );
// the above line gives an error saying that newAis might not have been intialized
} else if( outputFormat == "WAVE") {
AudioSystem.write(newAIS, AudioFileFormat.Type.WAVE, new File(outLoc) );
// the above line gives an error saying that newAis might not have been intialized
} else if( outputFormat == "AU") {
AudioSystem.write(newAIS, AudioFileFormat.Type.AU, new File(outLoc) );
// the above line gives an error saying that newAis might not have been intialized
} else if( outputFormat == "SND") {
AudioSystem.write(newAIS, AudioFileFormat.Type.SND, new File(outLoc) );
// the above line gives an error saying that newAis might not have been intialized
}
} catch( Exception exc ){
}
在上面的代码片段中,我声明了一个 AudioInputStream
类型的变量 newAIS
。 (从开始算起的第 12 条语句) 在下一个语句中,变量 newAIS
被初始化。当我到达 if-else
部分时,变量 newAIS
被认为是 IDE 未初始化的,并且它给出一个错误,指出 newAis 可能尚未初始化 为什么会这样?变量 newAIS
具有函数作用域。
另一方面,如果我声明变量 newAIS
global ,IDE 不会发现错误。
为什么会发生这种情况?
最佳答案
是的,它在范围内,但它可能尚未初始化 - 如果发生异常,那么您只需打印出异常并继续,而不是为变量分配值。在这种情况下,您希望 newAIS
具有什么值(value)?
在读取局部变量之前会检查其是否明确赋值,但实例/静态变量则不会。
请注意,如果您没有继续处理异常,而是向调用者抛出另一个异常,或者只是一开始就没有捕获它,或者返回了,那就好了。目前尚不清楚您真正想要处理什么异常 - 捕获 Exception
一般来说是一种不好的做法。
您可以只为变量分配一个值作为开头:
AudioInputStream newAIS = null;
...但是如果作业失败,您真的想继续吗?
另请注意,您当前正在使用 ==
比较字符串,这也是一个坏主意。这:
if (outputFormat == "AIFF")
可能应该是:
if (outputFormat.equals("AIFF"))
关于java - 当变量被声明为具有函数作用域时,我收到类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7385903/