I can't figure out what's wrong, my logic seems correct
I know that what's messing up is my checkIfEdu method. Everything else is fine because I've tried it without that method. However, it's reading all the data into the InvalidStudentEmails file and its because of that method! i know it, everything else if fine because when I take that method out, it does everything correctly. Please help!!!
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.p开发者_JAVA百科rintf("%-20s%20s", "Name", "Email Address (Invalid)");
invalidOutput.println();
invalidOutput.println();
}
}
Here are my methods
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();
}
}
you compare strings with the equals() method. Using '==' is comparing object references
Did you check what's the checkIfEdu()
return
?
Another thing is, as I have tried to run your checkIfEdu()
it always return false. Because you are comparing it as reference.
To compare String, this should be like this:
if (checkWord.equals("edu")) {
精彩评论