CharAt index error while reading through text file in Java












0














I'm getting some confusing errors when I iterate through this entire enable1 txt file (https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt) to check if it meets the "I before E except after C" English word 'rule'. I noticed the code succeeds when I remove the "-1" from charAt(indexEI - 1) that I starred below (****).



Any ideas why this might be? The errors just say "at java.lang.String.charAt (String.java: 658)", "Main.ibeforeE", and "at Main.main" in seemingly random spots in the "e" section of the iteration. Then it says varcacheexecutor-snippetsrun.xml:53: Java returned: 1 BUILD FAILED at the very end.



I'm quite new to Java so any other constructive criticism is appreciated as well. Thanks!



Main:



import java.util.Scanner;
import java.util.ArrayList;

public class Main {

public static void main(String args) {

EnableWord test = new EnableWord();
test.EnableWords();


Scanner read = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list = test.getList();


int x = 0;
int falseCounter = 0;

while (x < list.size()) {
System.out.print(list.get(x) + ": ");

String input = list.get(x);

if (input.equals("x")) {
break;
} else {
System.out.println(iBeforeE(input));
if(!iBeforeE(input)) {
falseCounter++;
}
x++;
}
}

System.out.println(falseCounter);
}

public static boolean iBeforeE(String input) {


if (!input.contains("ie") && !input.contains("ei")) {
return true;
}

if (input.contains("ie")) {
int indexIE = input.indexOf("ie");
Character searchIE = input.charAt(indexIE - 1);
if (!searchIE.toString().equals("c")) {
return true;
}

} else if (input.contains("ei")) {
int indexEI = input.indexOf("ei");
****Character searchEI = input.charAt(indexEI - 1);****
if (searchEI.toString().equals("c")) {
return true;
}
}


return false;

}


Class EnableWord:



}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EnableWord {

private ArrayList<String> list;
private Scanner s;
private File file;

public EnableWord() {
}

public void EnableWords() {

try {
this.s = new Scanner(this.file = new File("enable1.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(EnableWord.class.getName()).log(Level.SEVERE, null, ex);
}
this.list = new ArrayList<>();
while (s.hasNext()) {
list.add(s.next());
}
s.close();

}

public void printWords() {

for (String word : list) {
System.out.println(word);
}

}

public ArrayList<String> getList() {

ArrayList<String> newList = new ArrayList<String>();

for (String word : list) {
newList.add(word);

}
return list;
}

}









share|improve this question






















  • There should be one line above the "at java.lang.String.charAt..." in the error message. Please edit your post to include this
    – GBlodgett
    Nov 20 at 16:53


















0














I'm getting some confusing errors when I iterate through this entire enable1 txt file (https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt) to check if it meets the "I before E except after C" English word 'rule'. I noticed the code succeeds when I remove the "-1" from charAt(indexEI - 1) that I starred below (****).



Any ideas why this might be? The errors just say "at java.lang.String.charAt (String.java: 658)", "Main.ibeforeE", and "at Main.main" in seemingly random spots in the "e" section of the iteration. Then it says varcacheexecutor-snippetsrun.xml:53: Java returned: 1 BUILD FAILED at the very end.



I'm quite new to Java so any other constructive criticism is appreciated as well. Thanks!



Main:



import java.util.Scanner;
import java.util.ArrayList;

public class Main {

public static void main(String args) {

EnableWord test = new EnableWord();
test.EnableWords();


Scanner read = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list = test.getList();


int x = 0;
int falseCounter = 0;

while (x < list.size()) {
System.out.print(list.get(x) + ": ");

String input = list.get(x);

if (input.equals("x")) {
break;
} else {
System.out.println(iBeforeE(input));
if(!iBeforeE(input)) {
falseCounter++;
}
x++;
}
}

System.out.println(falseCounter);
}

public static boolean iBeforeE(String input) {


if (!input.contains("ie") && !input.contains("ei")) {
return true;
}

if (input.contains("ie")) {
int indexIE = input.indexOf("ie");
Character searchIE = input.charAt(indexIE - 1);
if (!searchIE.toString().equals("c")) {
return true;
}

} else if (input.contains("ei")) {
int indexEI = input.indexOf("ei");
****Character searchEI = input.charAt(indexEI - 1);****
if (searchEI.toString().equals("c")) {
return true;
}
}


return false;

}


Class EnableWord:



}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EnableWord {

private ArrayList<String> list;
private Scanner s;
private File file;

public EnableWord() {
}

public void EnableWords() {

try {
this.s = new Scanner(this.file = new File("enable1.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(EnableWord.class.getName()).log(Level.SEVERE, null, ex);
}
this.list = new ArrayList<>();
while (s.hasNext()) {
list.add(s.next());
}
s.close();

}

public void printWords() {

for (String word : list) {
System.out.println(word);
}

}

public ArrayList<String> getList() {

ArrayList<String> newList = new ArrayList<String>();

for (String word : list) {
newList.add(word);

}
return list;
}

}









share|improve this question






















  • There should be one line above the "at java.lang.String.charAt..." in the error message. Please edit your post to include this
    – GBlodgett
    Nov 20 at 16:53
















0












0








0







I'm getting some confusing errors when I iterate through this entire enable1 txt file (https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt) to check if it meets the "I before E except after C" English word 'rule'. I noticed the code succeeds when I remove the "-1" from charAt(indexEI - 1) that I starred below (****).



Any ideas why this might be? The errors just say "at java.lang.String.charAt (String.java: 658)", "Main.ibeforeE", and "at Main.main" in seemingly random spots in the "e" section of the iteration. Then it says varcacheexecutor-snippetsrun.xml:53: Java returned: 1 BUILD FAILED at the very end.



I'm quite new to Java so any other constructive criticism is appreciated as well. Thanks!



Main:



import java.util.Scanner;
import java.util.ArrayList;

public class Main {

public static void main(String args) {

EnableWord test = new EnableWord();
test.EnableWords();


Scanner read = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list = test.getList();


int x = 0;
int falseCounter = 0;

while (x < list.size()) {
System.out.print(list.get(x) + ": ");

String input = list.get(x);

if (input.equals("x")) {
break;
} else {
System.out.println(iBeforeE(input));
if(!iBeforeE(input)) {
falseCounter++;
}
x++;
}
}

System.out.println(falseCounter);
}

public static boolean iBeforeE(String input) {


if (!input.contains("ie") && !input.contains("ei")) {
return true;
}

if (input.contains("ie")) {
int indexIE = input.indexOf("ie");
Character searchIE = input.charAt(indexIE - 1);
if (!searchIE.toString().equals("c")) {
return true;
}

} else if (input.contains("ei")) {
int indexEI = input.indexOf("ei");
****Character searchEI = input.charAt(indexEI - 1);****
if (searchEI.toString().equals("c")) {
return true;
}
}


return false;

}


Class EnableWord:



}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EnableWord {

private ArrayList<String> list;
private Scanner s;
private File file;

public EnableWord() {
}

public void EnableWords() {

try {
this.s = new Scanner(this.file = new File("enable1.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(EnableWord.class.getName()).log(Level.SEVERE, null, ex);
}
this.list = new ArrayList<>();
while (s.hasNext()) {
list.add(s.next());
}
s.close();

}

public void printWords() {

for (String word : list) {
System.out.println(word);
}

}

public ArrayList<String> getList() {

ArrayList<String> newList = new ArrayList<String>();

for (String word : list) {
newList.add(word);

}
return list;
}

}









share|improve this question













I'm getting some confusing errors when I iterate through this entire enable1 txt file (https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt) to check if it meets the "I before E except after C" English word 'rule'. I noticed the code succeeds when I remove the "-1" from charAt(indexEI - 1) that I starred below (****).



Any ideas why this might be? The errors just say "at java.lang.String.charAt (String.java: 658)", "Main.ibeforeE", and "at Main.main" in seemingly random spots in the "e" section of the iteration. Then it says varcacheexecutor-snippetsrun.xml:53: Java returned: 1 BUILD FAILED at the very end.



I'm quite new to Java so any other constructive criticism is appreciated as well. Thanks!



Main:



import java.util.Scanner;
import java.util.ArrayList;

public class Main {

public static void main(String args) {

EnableWord test = new EnableWord();
test.EnableWords();


Scanner read = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list = test.getList();


int x = 0;
int falseCounter = 0;

while (x < list.size()) {
System.out.print(list.get(x) + ": ");

String input = list.get(x);

if (input.equals("x")) {
break;
} else {
System.out.println(iBeforeE(input));
if(!iBeforeE(input)) {
falseCounter++;
}
x++;
}
}

System.out.println(falseCounter);
}

public static boolean iBeforeE(String input) {


if (!input.contains("ie") && !input.contains("ei")) {
return true;
}

if (input.contains("ie")) {
int indexIE = input.indexOf("ie");
Character searchIE = input.charAt(indexIE - 1);
if (!searchIE.toString().equals("c")) {
return true;
}

} else if (input.contains("ei")) {
int indexEI = input.indexOf("ei");
****Character searchEI = input.charAt(indexEI - 1);****
if (searchEI.toString().equals("c")) {
return true;
}
}


return false;

}


Class EnableWord:



}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EnableWord {

private ArrayList<String> list;
private Scanner s;
private File file;

public EnableWord() {
}

public void EnableWords() {

try {
this.s = new Scanner(this.file = new File("enable1.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(EnableWord.class.getName()).log(Level.SEVERE, null, ex);
}
this.list = new ArrayList<>();
while (s.hasNext()) {
list.add(s.next());
}
s.close();

}

public void printWords() {

for (String word : list) {
System.out.println(word);
}

}

public ArrayList<String> getList() {

ArrayList<String> newList = new ArrayList<String>();

for (String word : list) {
newList.add(word);

}
return list;
}

}






java indexof charat






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 16:40









Nick Green

52




52












  • There should be one line above the "at java.lang.String.charAt..." in the error message. Please edit your post to include this
    – GBlodgett
    Nov 20 at 16:53




















  • There should be one line above the "at java.lang.String.charAt..." in the error message. Please edit your post to include this
    – GBlodgett
    Nov 20 at 16:53


















There should be one line above the "at java.lang.String.charAt..." in the error message. Please edit your post to include this
– GBlodgett
Nov 20 at 16:53






There should be one line above the "at java.lang.String.charAt..." in the error message. Please edit your post to include this
– GBlodgett
Nov 20 at 16:53














2 Answers
2






active

oldest

votes


















0














There are words in your list that start with ei (ex: eicosanoid)
When your program gets to these words, it finds the index of 'ei' to be 0. So the value of "indexEI - 1" is negative 1, an invalid index.



you could fix it by checking if indexEI is > 0 before trying to check the previous character is a 'c':



if (indexEI == 0 || input.charAt(indexEI - 1).toString().equals("c")) {
return true;
}





share|improve this answer





















  • Ah I should have known! Thank you so much!
    – Nick Green
    Nov 20 at 17:37










  • Your file doesn't have any words that start with 'ie', but it would be good to use the same logic in the 'ie' block as well, or better yet extract that logic to a method:
    – Blair
    Nov 20 at 20:47



















0














As soon as a word starts with 'ie' or 'ei' then input.charAt(indexIE - 1) will generate an error since indexIE then is 0.



I am not sure what you want to do in your code but some kind of check is needed



if (indexIE == 0) {

} else {
//current code
}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397598%2fcharat-index-error-while-reading-through-text-file-in-java%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    There are words in your list that start with ei (ex: eicosanoid)
    When your program gets to these words, it finds the index of 'ei' to be 0. So the value of "indexEI - 1" is negative 1, an invalid index.



    you could fix it by checking if indexEI is > 0 before trying to check the previous character is a 'c':



    if (indexEI == 0 || input.charAt(indexEI - 1).toString().equals("c")) {
    return true;
    }





    share|improve this answer





















    • Ah I should have known! Thank you so much!
      – Nick Green
      Nov 20 at 17:37










    • Your file doesn't have any words that start with 'ie', but it would be good to use the same logic in the 'ie' block as well, or better yet extract that logic to a method:
      – Blair
      Nov 20 at 20:47
















    0














    There are words in your list that start with ei (ex: eicosanoid)
    When your program gets to these words, it finds the index of 'ei' to be 0. So the value of "indexEI - 1" is negative 1, an invalid index.



    you could fix it by checking if indexEI is > 0 before trying to check the previous character is a 'c':



    if (indexEI == 0 || input.charAt(indexEI - 1).toString().equals("c")) {
    return true;
    }





    share|improve this answer





















    • Ah I should have known! Thank you so much!
      – Nick Green
      Nov 20 at 17:37










    • Your file doesn't have any words that start with 'ie', but it would be good to use the same logic in the 'ie' block as well, or better yet extract that logic to a method:
      – Blair
      Nov 20 at 20:47














    0












    0








    0






    There are words in your list that start with ei (ex: eicosanoid)
    When your program gets to these words, it finds the index of 'ei' to be 0. So the value of "indexEI - 1" is negative 1, an invalid index.



    you could fix it by checking if indexEI is > 0 before trying to check the previous character is a 'c':



    if (indexEI == 0 || input.charAt(indexEI - 1).toString().equals("c")) {
    return true;
    }





    share|improve this answer












    There are words in your list that start with ei (ex: eicosanoid)
    When your program gets to these words, it finds the index of 'ei' to be 0. So the value of "indexEI - 1" is negative 1, an invalid index.



    you could fix it by checking if indexEI is > 0 before trying to check the previous character is a 'c':



    if (indexEI == 0 || input.charAt(indexEI - 1).toString().equals("c")) {
    return true;
    }






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 20 at 17:01









    Blair

    665




    665












    • Ah I should have known! Thank you so much!
      – Nick Green
      Nov 20 at 17:37










    • Your file doesn't have any words that start with 'ie', but it would be good to use the same logic in the 'ie' block as well, or better yet extract that logic to a method:
      – Blair
      Nov 20 at 20:47


















    • Ah I should have known! Thank you so much!
      – Nick Green
      Nov 20 at 17:37










    • Your file doesn't have any words that start with 'ie', but it would be good to use the same logic in the 'ie' block as well, or better yet extract that logic to a method:
      – Blair
      Nov 20 at 20:47
















    Ah I should have known! Thank you so much!
    – Nick Green
    Nov 20 at 17:37




    Ah I should have known! Thank you so much!
    – Nick Green
    Nov 20 at 17:37












    Your file doesn't have any words that start with 'ie', but it would be good to use the same logic in the 'ie' block as well, or better yet extract that logic to a method:
    – Blair
    Nov 20 at 20:47




    Your file doesn't have any words that start with 'ie', but it would be good to use the same logic in the 'ie' block as well, or better yet extract that logic to a method:
    – Blair
    Nov 20 at 20:47













    0














    As soon as a word starts with 'ie' or 'ei' then input.charAt(indexIE - 1) will generate an error since indexIE then is 0.



    I am not sure what you want to do in your code but some kind of check is needed



    if (indexIE == 0) {

    } else {
    //current code
    }





    share|improve this answer


























      0














      As soon as a word starts with 'ie' or 'ei' then input.charAt(indexIE - 1) will generate an error since indexIE then is 0.



      I am not sure what you want to do in your code but some kind of check is needed



      if (indexIE == 0) {

      } else {
      //current code
      }





      share|improve this answer
























        0












        0








        0






        As soon as a word starts with 'ie' or 'ei' then input.charAt(indexIE - 1) will generate an error since indexIE then is 0.



        I am not sure what you want to do in your code but some kind of check is needed



        if (indexIE == 0) {

        } else {
        //current code
        }





        share|improve this answer












        As soon as a word starts with 'ie' or 'ei' then input.charAt(indexIE - 1) will generate an error since indexIE then is 0.



        I am not sure what you want to do in your code but some kind of check is needed



        if (indexIE == 0) {

        } else {
        //current code
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 16:58









        Joakim Danielson

        6,8173623




        6,8173623






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397598%2fcharat-index-error-while-reading-through-text-file-in-java%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin