我知道弄糟的是我的checkIfEdu方法。其他一切都很好,因为我没有那种方法就尝试过。但是,由于该方法,它正在将所有数据读入InvalidStudentEmails文件及其中!我知道,其他一切都很好,因为当我采取这种方法时,它会正确地完成所有事情。请帮忙!!!
import java.util.Scanner;
public class CheckStudentEmail
{
public static void main (String[] args) throws Exception
{
java.io.File filein = new java.io.File("StudentEmailData.txt");
java.io.File fileout1 = new java.io.File("ValidStudentEmails.txt");
java.io.File fileout2 = new java.io.File("InvalidStudentEmails.txt");
Scanner input = new Scanner(filein);
java.io.PrintWriter validOutput = new java.io.PrintWriter(fileout1);
java.io.PrintWriter invalidOutput = new java.io.PrintWriter(fileout2);
writeHeadings(validOutput, invalidOutput);
StudentEmail student = new StudentEmail();
while (input.hasNext())
{
student.readStudentData(input);
if (student.checkPeriod() == true && student.checkAtSymbol() == true
&& student.checkIfEdu() == true)
student.writeEmails(validOutput);
else
student.writeEmails(invalidOutput);
}
input.close();
validOutput.close();
invalidOutput.close();
}
public static void writeHeadings(java.io.PrintWriter validOutput, java.io.PrintWriter invalidOutput)
{
validOutput.printf("%-20s%20s", "Name", "Email Address (Valid)"); validOutput.println(); validOutput.println();
invalidOutput.printf("%-20s%20s", "Name", "Email Address (Invalid)");
invalidOutput.println();
invalidOutput.println();
}
}
以下是我的方法
import java.util.Scanner;
public class StudentEmail
{
private String stuName;
private String stuEmail;
StudentEmail()
{}
StudentEmail(String name, String email)
{
stuName = name;
stuEmail = email;
}
public void readStudentData(Scanner input)
{
stuName = input.next();
stuEmail = input.next();
}
public boolean checkPeriod()
{
if (stuEmail.indexOf(".") != -1)
return true;
else
return false;
}
public boolean checkAtSymbol()
{
int atSymbol;
if (stuEmail.indexOf('@') != -1)
{
atSymbol = stuEmail.indexOf('@');
if (stuEmail.indexOf('@', atSymbol+1) != -1)
return false;
else
return true;
}
else
return false;
}
public boolean checkIfEdu()
{
int lengthOfEmail = stuEmail.length();
int position = lengthOfEmail - 3;
String checkWord = stuEmail.substring(position);
if (checkWord == "edu")
return true;
else
return false;
}
public void writeEmails(java.io.PrintWriter output)
{
output.printf("%-20s%20s", stuName, stuEmail);
output.println();
}
}
答案 0 :(得分:4)
将字符串与equals()方法进行比较。使用'=='比较对象引用
答案 1 :(得分:1)
您是否检查了checkIfEdu()
return
的内容是什么?
另一件事是,因为我试图运行你的checkIfEdu()
它总是返回false。因为您将其作为参考进行比较。
要比较字符串,这应该是这样的:
if (checkWord.equals("edu")) {