简体   繁体   中英

Java Index Out of Bounds Exception

I'm getting an IndexOutOfBoundsException at the line that calls for my custom fonction: motCars = remplaceTirets(motAlea, motCars, lettreDon); . This function is supposed to turn one or more of the dashes into the letter if the given letter equals the letter in the word) and a line in the actual function where it says: tempo += tirets.charAt(j);

The result is: _ _ _ _ _ _ _ (the amount of these dashes depends on the word chosen by the program, which works and then it asks to give a letter but when I give a letter I get:

Exception in thread 'main' java.lang.String IndexOutOfBoundsException. String Index out of range: 1.

It's partly in french because I live in Quebec. But I'm hoping that it doesn't matter because the french words just concern the strings and words, not the logic of java. I'm a beginner and overwhelmed with all the advice on all the forums on Java. Any specific advice will be welcome.

Thanks in advance for taking the time to have a look !

Anita

import java.util.Scanner; 

class Tp {

public static void main( String[] args ) throws Exception {

Scanner clavier = new Scanner(System.in);
String motAlea = "";                                
String motCars = "";                
char lettreDon = Character.UNASSIGNED;              
String tempo = "";                                  
String invite = "";
String tirets = "";
int l = 0;                                  
int m = 0;                              

final String ANNONCE  = "J'ai choisi un mot a deviner\n";
final String INSTRUCT = "Entrez une lettre a la fois. L'indice d'essais: 15.\n";
final String INVITE   = "\tEntrez une lettre: ";
final String BRAVO    = "BRAVO ! Le mot a deviner etait: ";
final String DESOLE   = "DESOLE...Vous avez perdu..."; 

String[] vingtMots = {  "WATTHEUREMETRE", "HELIOGRAPH", "GRENOUILLERE",     "CONTRAROTATIF", 
                        "CUISSARDE", "BRIGANTINE", "AVITAILLEUR", "ENTREDOUBLURE", 
                        "GALLETAGE", "OEUILLERE", "CREMAILLERE", "HALTEROPHILIE", 
                        "MARTINGALE", "EMPENNAGE", "ENCOCHAGE", "DECLENCHEUR", 
                        "BIMETALLIQUE", "PIVOTEMENT", "DECLINAISON", "CROISILLON"
                        }; // tableau string        

int indexAlea = 0; 
indexAlea = (int)(Math.random() * 20) + 1;

motAlea = vingtMots[indexAlea]; 

for (l = 0; l < motAlea.length(); l++) { 
    tempo += "_";
    motCars = tempo;
} // for

System.out.print(ANNONCE);
System.out.print(INSTRUCT);
l = 0;

do {
    if (motCars.equals(motAlea)) {
    System.out.print(BRAVO + motAlea + ", " + "devine en " + m + 
    " tentatives");
    System.exit(0);
    } // if

    if (l == 15) {
        System.out.print("\n" + DESOLE + "Le mot a devine etait: " + 
        motAlea + ". " + "Au revoir... "); 
        System.exit(0); 
    } // if

    for (int i = 0; i < motAlea.length(); i++) { 
    System.out.print(motCars.charAt(i) + " ");   
    } // for

    m = l + 1;
    invite = "\t" + INVITE + m + ">  :";

    lettreDon = lecture(invite); 

    motCars = remplaceTirets(motAlea, motCars, lettreDon);

    l++;    

 } // do
    while (l < 16); {
    System.out.print("\n" + DESOLE + "Le mot a devine etait: " + motAlea + ". " 
    + "Au revoir... "); 
    } // while


} //main(...)

public static char lecture(String invite1){

Scanner clavier = new Scanner(System.in);
final String ERREUR = "La valeur entree est erronnee !\nReprenez-vous...";
final String VIDE = " ";
String retour = "";

    do { 
        try {
        System.out.print(invite1);
        retour = clavier.nextLine().trim(); // Mise en forme;

            for (int k = 0; k < retour.length(); k++) {

                if(Character.isLetter(retour.charAt(k))) {
                return retour.toUpperCase().charAt(0);
                } // if
            } // for
        } // try
        catch (Exception e) {
        System.out.print(ERREUR);
        }               
    }// do
    while (!retour.equals(VIDE)); {
    retour = "X";
    return retour.charAt(0);
    } // while              
} // lecture(...)

public static String remplaceTirets(String motAlea1, String tirets, 
char lettre) {
String retour;  
String tempo = ""; 

    for (int j = 0; j < motAlea1.length(); j++) { 

        String lettre1 = Character.toString(lettre);
        if (motAlea1.charAt(j) != lettre1.charAt(0)) {
        tempo += tirets.charAt(j);
        } // if     
            else {
            tempo += lettre1.charAt(0); 
            } // else   
    tirets = tempo; 
    } // for    
    return retour = tirets;         
} //remplaceTirets(...)

}//Tp               

The line

tirets = tempo;

should be out of the for loop.

change your code to

for (int j = 0; j < motAlea1.length(); j++) { 
    String lettre1 = Character.toString(lettre);
    if (motAlea1.charAt(j) != lettre1.charAt(0)) {
        tempo += tirets.charAt(j);
    } // if     
        else {
        tempo += lettre1.charAt(0); 
    } // else   
    //tirets = tempo; //REMOVE THIS LINE
} // for 
tirets = tempo; //ADD THIS LINE

You are accessing a position in tirets based on the length of motAlea1 . I expect that motAlea1.length() > tirets.length() .

for (int j = 0; j < motAlea1.length(); j++) { 

    String lettre1 = Character.toString(lettre);

    if (motAlea1.charAt(j) != lettre1.charAt(0)) {
        tempo += tirets.charAt(j); //THIS COULD FAIL!!!
    }else{
        tempo += lettre1.charAt(0); 
    }
    tirets = tempo; 
}

In this loop:

for (int j = 0; j < motAlea1.length(); j++) { 

    String lettre1 = Character.toString(lettre);
    if (motAlea1.charAt(j) != lettre1.charAt(0)) {
    tempo += tirets.charAt(j);
    } // if     
        else {
        tempo += lettre1.charAt(0); 
        } // else   
tirets = tempo; 
} // for    

String tirets is shorter than motAlea1 and so you're trying to retrieve a character beyond its end .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM