“缺少退货声明”,带有while循环

时间:2014-07-26 02:43:37

标签: java return

此代码遇到返回错误。我很感激被告知如何解决它,更重要的是比前者解释为什么有必要这样做。我的教授在解释许多事情是如何工作的时候做了一个非常好的工作,所以现在我觉得我需要学习很多应该知道的事情。谢谢大家!

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;
    }

}

3 个答案:

答案 0 :(得分:1)

如果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

答案 1 :(得分:0)

本声明

 while (e == temp)
   return null;

如果(且仅当)e具有带temp的引用标识,则返回null。所以,你应该使用equals。最后,如果从未输入该循环,则需要返回一些内容(就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;

答案 2 :(得分:0)

您需要确保无论您的代码中发生了什么,都会返回一些内容。如果您有条件语句(if)或循环(forwhile),则需要确保对于条件块或循环的情况有一个return语句从不执行。

例如:

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