"Missing Return Statement" ,带 while 循环



此代码遇到返回错误。如果有人告诉我如何解决这个问题,我会很感激,比前者更重要的是解释为什么有必要这样做。我的教授在解释很多东西的工作原理方面做得很差,所以现在我觉得我需要学习很多应该已经知道的东西。谢谢大家!

import java.io.*;               //Imports any file operation (ie Reading or Writing)
import java.util.Scanner;       //Imports scanner class
import javax.swing.JOptionPane; //Import JOptionPane to allow dialog boxes
public class program7
{
    public String MakeFile() throws IOException
    {
        String NameofDataFile, inputted_text, temp, e;
        temp = "";
        NameofDataFile=JOptionPane.showInputDialog("Enter the name of the file to be opened: ");    //creates file with entered name
        /*allows file to be written in*/
        PrintWriter FileObj = new PrintWriter (new FileWriter (NameofDataFile));
        inputted_text=JOptionPane.showInputDialog("Enter a String: ");                                    //asks user for a string
        e = inputted_text;
        while (e == temp)
            return null;
    }
}

如果e不等于temp,则不存在return语句。您可能还想使用if,因为while用于循环。但就你写的而言,这不是一个循环。程序将在进入while后立即返回。或者你的代码还没有完成,你想在while里面放一些东西。然后,您应该在while之后添加{}括号块。

while(e.equals(temp)) {
// do something
}
return null; // maybe you shouldn't return null. You should return a String

语句

 while (e == temp)
   return null;

将返回null当(且仅当)e与temp具有引用同一性,因此,您应该使用等号。最后,如果该循环从未进入,则需要返回一些内容(对于JRE来说是一个有效的路径)-

 if (e.equals(temp)) {
   // if e is equal to temp, no need for a while as far as I see.
   return null;
 }
 return e;

无论代码中发生了什么,您都需要确保返回一些东西。如果您有条件语句(if)或循环(forwhile),则需要确保在条件块或循环从未执行的情况下有返回语句。

例如:

public int example(int n){
    while (n > 0)
         return n;
    //what happens if n is <= 0?
}

最新更新