【发布时间】:2014-07-26 02:43:37
【问题描述】:
此代码遇到返回错误。我会很感激被告知如何解决它,并且比前者更重要的是解释为什么有必要这样做。我的教授在解释很多事情是如何运作的方面做得非常出色,所以现在我觉得我需要学习很多应该已经知道的东西。谢谢大家!
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怎么办?它不会。阅读:how to compare strings in Java. -
你真的不需要专业人士的帮助。在上面的代码中,只有进入while循环才会执行return。如果代码没有进入 while 循环,那么您不会为这种情况返回任何内容。顺便说一句,你为什么不总是把代码放在
{}里面?我不明白教授怎么能解释得这么糟糕。 -
题外话,但你应该知道:Java 类应该大写为
UppercaseStartingCamelCase。变量名应大写为lowercaseStartingCamelCase。所以你的类应该是Program7,方法应该是makeFile(),你的变量应该是nameOfDataFile、fileObj和inputtedText。但是,我们直接称它们为dataFileName、file和input怎么样(更简洁,更少冗余)。