java - StringIndexout of range -
i got error: stringindex out of range: -1 error line string anemail = linefromfile.substring(s+1, e). can see im trying print part of line in input file doesn't work. can me explain why?
import java.io.*; 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: program start 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 input file while(true) { if(!fin.ready()) break; string linefromfile; linefromfile = fin.readline(); int s, e, hasdot; (int = 0; < linefromfile.length(); i++) // each char in string... { if(linefromfile.charat(i)=='@') { for(s=i;s>-1;s--) { if(isvalidemailcharacter(linefromfile.charat(s))==false) for(e=1; e< linefromfile.length(); e++) { if(isvalidemailcharacter(linefromfile.charat(e))==false) { string anemail = linefromfile.substring(s+1, e); system.out.println(anemail); break; } } } } } } fin.close(); printwriter fout; fout = new printwriter(new filewriter(nameout)); fout.close(); } }
suppose line has 10 characters. i
loop goes 0 9.
you have s
loop, goes i
0.
and inside that, access `linefromfile.substring(s+1);
so when i
9, s
loop starts @ 9, , try access index 9+1, index 10, outside of line.
Comments
Post a Comment