基本算法是我有一个输入文件,其中包含多个句子,每个句子都在每一行。我想打印出从位置s到e的句子的一部分,但是使用下面的代码,它打印出空行有人能告诉我我的错误在哪里吗?
public class Email13
{
static boolean isValidEmailCharacter(char c)
{
boolean result = false;
if((c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c>='0'&&c<='9')||(c=='.')||(c=='-')||(c=='+'))
result = true;
return result;
}
public static void main(String[] args) throws Exception{
BufferedReader cin, fin;
cin = new BufferedReader(new InputStreamReader(System.in));
//Description
System.out.println("Programmer: Minh Nguyen");
System.out.println("Description: This program is to start the final project.");
System.out.println();
String nameIn, nameOut, deIn, deOut;
nameIn="";
nameOut="";
deIn = "fileContainingEmails.txt";
System.out.print("Enter input filename [default:" + deIn + "]: ");
nameIn = cin.readLine();
if(nameIn.compareTo("")==0){
nameIn = deIn;
deOut = "copyPasteMyEmails.txt";
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = deOut;
}
else if(nameIn.compareTo("")>0){
deOut = nameIn;
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = nameIn;
}
fin = new BufferedReader(new FileReader(nameIn));
//Read the input file
while(true)
{
if(!fin.ready()) break;
String lineFromFile;
lineFromFile = fin.readLine();
int s, e, hasDot;
for (int i = 0; i < lineFromFile.length(); i++) // for each char in the string...
{
if(lineFromFile.charAt(i)=='@')
{
for(s=i;s>-1;s--)
{
if(isValidEmailCharacter(lineFromFile.charAt(s))==false)
break;
}
for(e=i; e< lineFromFile.length(); e++)
{
if(isValidEmailCharacter(lineFromFile.charAt(e))==false)
break;
}
String anEmail = lineFromFile.substring(s,e);
System.out.println(anEmail);
}
}
}
fin.close();
PrintWriter fout;
fout = new PrintWriter(new FileWriter(nameOut));
fout.close();
}
}
答案 0 :(得分:0)
当你执行s--时,如果你的所有角色都是好的,那么for循环可以用s等于-1来完成。同样的问题可能影响e ++。但是使用子字符串的最后一个索引,你想要比char位置多一个。即String cat =“Cat”; String temp = cat.substring(0,1)返回C.
为了检查边界,请尝试:
for(s=i;s>-1;s--)
{
if(isValidEmailCharacter(lineFromFile.charAt(s))==false)
break;
}
if(s <0)// if it never hit break s is now == -1
s=0;
请记住循环的基础知识。如果我做了
for(a=0; a<10; a++)
;
当我完成时,等于10。它不会在值10上执行循环,因为当它为10时它会失败一个&lt; 10,但确实以a = 10完成。
答案 1 :(得分:0)
I try this but it doesn't work:(
s=i;
while(s>-1)
{
if(isValidEmailCharacter(lineFromFile.charAt(s))==false)
break;
else
s = 0;
s--;
}
e=i;
while(e< lineFromFile.length())
{
if(isValidEmailCharacter(lineFromFile.charAt(e))==false)
break;
else
e = lineFromFile.length();
e++;`enter code here`
}