开发者

Java if statements

How come the last line of this code is not picking up the string filename in the开发者_如何学Go code?

if (ressound == R.id.sound1) {
    String filename = "sound1" + ".ogg";
} else {
    String filename = "sound1" + ".ogg";
}
boolean exists = (new File(path)).exists();   
if (!exists) { new File(path).mkdirs(); }   

FileOutputStream save;
try { 
    save = new FileOutputStream(path + filename);  


You're declaring the variable in the scope of the if respectively else branch. Out of this scope the variable is not accessible.

Use this instead:

String filename;
    if (ressound == R.id.sound1) {
           filename="sound1"+".ogg";
       } else{
            filename="sound1"+".ogg";
       }
             boolean exists = (new File(path)).exists();   
             if (!exists){new File(path).mkdirs();}   

             FileOutputStream save;
             try { 
              save = new FileOutputStream(path+filename);  


Your code as it is won't even compile as both filename variables you've declared are gone out of scope where you create the FileOutputStream.

I would do this:

private String getFilename() {
    if (ressound == R.id.sound1) {
        return "sound1"+".ogg";
    }
    return "sound1"+".ogg";
}

And then call it from your other method:

boolean exists = (new File(path)).exists();   
if (!exists){ new File(path).mkdirs(); }   

FileOutputStream save;
try { 
    save = new FileOutputStream(path+getFilename()); 

As I've said in the comment above I don't know why you assign the same value to filename in both cases, as in getFilename() always returns "sound1.ogg". Maybe that was your bug but I left it as you have it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜