Properties file and array - java

Good afternoon, I have a problem. When reading a property file, and passing it to an array, it looks like the array is repeated until you finish reading the document, as shown in the image
I'm supposed to read the properties from a txt file that contains them and pass the artist's name to an array of size 10.
Here the methods used by the program
/**
* Carga la información inicial del karaoke.
*/
private void cargarKaraoke() {
try {
Properties datos = new Properties();
FileInputStream in = new FileInputStream(RUTA_ARCHIVO);
datos.load(in);
in.close();
int numArtistas = Integer.parseInt(datos.getProperty("total.artistas"));
for(int i = 1; i <= numArtistas; i++) {
String nombre = datos.getProperty("artista" + i + ".nombre");
String categoria = datos.getProperty("artista" + i + ".categoria");
String imagen = datos.getProperty("artista" + i + ".imagen");
karaoke.agregarArtista(nombre, categoria, imagen);
int numCanciones = Integer.parseInt(datos.getProperty("artista"
+ i + ".total.canciones"));
for(int j = 1; j <= numCanciones; j++) {
String cancion = datos.getProperty("artista" + i + ".cancion"
+ j + ".nombre");
int duracion = Integer.parseInt(datos.getProperty("artista"
+ i + ".cancion" + j + ".duracion"));
String letra = datos.getProperty("artista" + i + ".cancion"
+ j + ".letra");
int dificultad = Integer.parseInt(datos.getProperty( "artista"
+ i + ".cancion" + j + ".dificultad"));
String genero = datos.getProperty("artista" + i + ".cancion"
+ j + ".genero");
String ruta = datos.getProperty("artista" + i + ".cancion"
+ j + ".ruta");
karaoke.agregarCancion(nombre, cancion, duracion, letra,
dificultad, genero, ruta);
}
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(this, "No fue posible cargar la información "
+ "inicial del karaoke " + e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void agregarArtista(String nombreArtista, String categoria, String imagen) {
for (int i = 0; i < artistas.length; i++) {
artistas[i] = new Artista(nombreArtista, categoria, imagen);
}
System.out.println(Arrays.toString(artistas));
}
public int agregarCancion(String nombre, int duracion, String letra, int dificultad,
String genero, String ruta) {
canciones.add(new Cancion(dificultad, duracion, genero, nombre, letra, ruta));
return 1;
}
But at the time of testing the results of the image appear.
Personally I think the problem is in the method to add artist, but I can not identify the problem.
Does anyone have any idea what's going on?

You can save all Artista obejcts in a List List<Artista> artistas = new ArrayList<Artista>() and change the Method agregarArtista to fill the list with the Artists Data:
public void agregarArtista(String nombreArtista, String categoria, String imagen) {
artistas.add(new Artista(nombreArtista, categoria, imagen));
System.out.println(artistas);
}
If You want only first 10 Artists then You could change the Method as below:
public void agregarArtista(String nombreArtista, String categoria, String imagen) {
if (artistas.size() < 10) {
artistas.add(new Artista(nombreArtista, categoria, imagen));
}
System.out.println(artistas);
}
If the result should be in a Array then You could convert List to an Array like this:
Artista[] artistasArray = artistas.toArray(new Artista[0]);

Related

How to optimized multiple for loops to make code more readable

I've written a method to read json and generate data based on different combination.
For example lets say I've 3 json parameter and i wanna pass different permutation of json data.
So combination would be :
1 - F,T,T
2 - T,F,T
3 - T,T,F
4 - T,T,T
I used negativeCaseList to get false data and postitiveCaseList to get true data.
My task is to optimize this code to make it more readable.
Any suggestion is highly appreciated.
for (int i = 0; i < negativeCaseList.size(); i++) {
if (!negativeCaseList.get(i).isEmpty()) {
ArrayList<?> negativeDataAsList = (ArrayList<?>) negativeCaseList.get(i);
for (int j = 0; j < negativeDataAsList.size(); j++) {
ParameterData negativeParameterData = (ParameterData) negativeDataAsList.get(j);
for (int k = 0; k < postitiveCaseList.size(); k++) {
ArrayList<?> positiveDataAsList = (ArrayList<?>) postitiveCaseList.get(k);
for (int l = 0; l < positiveDataAsList.size(); l++) {
ParameterData positiveParameterData = (ParameterData) positiveDataAsList.get(l);
if (Utility.validateString(negativeParameterData.getParameterName())) {
if (!negativeParameterData.getParameterName().equals(positiveParameterData.getParameterName())) {
if (!positiveParameterData.parameterType.startsWith("System")) {
dictionary.put(positiveParameterData.getParameterName(), positiveParameterData.getValue());
} else {
dictionary.put(positiveParameterData.getParameterName(), positiveParameterData.getValue());
}
paramName = positiveParameterData.getParameterName() + "," + paramName;
if (Utility.hasHTMLTags(positiveParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + positiveParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = positiveParameterData.getValue() + "," + paramValue;
}
} else {
dictionary.put(negativeParameterData.getParameterName(), negativeParameterData.getValue());
paramName = negativeParameterData.getParameterName() + "," + paramName;
if (Utility.hasHTMLTags(negativeParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + negativeParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = negativeParameterData.getValue() + "," + paramValue;
}
}
} else {
listofParameter = negativeParameterData.getValue();
if (Utility.hasHTMLTags(negativeParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + negativeParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = negativeParameterData.getValue() + "," + paramValue;
}
}
}
}
//json ="";
if (!dictionary.isEmpty()) {
json = ParameterTransform.ObjectToString(dictionary);
} else {
json = ParameterTransform.ObjectToString(listofParameter);
}
preData.putAll(Utils.fillTestDetailsInPreData(requestRule));
if (requestRule.getiRegistrationNo()) {
JSONObject stringToJson = new JSONObject(json);
json = securityObject.buildMainJson("10401", "f41f9ac6-1090-4851-bc7a-4a2355dd10c4",
stringToJson);
}
jsons.add(json);
app_logs.info("Json " + jsons);
//reportData.add(json+"|"+paramName+"|"+paramValue);
if (Utility.hasHTMLTags(json)) {
reportData.add("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + json + "</xmp>");
} else {
reportData.add(json);
}
pName.add(paramName.toString());
pValue.add(paramValue.toString());
app_logs.info("data " + reportData);
//app_logs.info("pName : " + pName.toString());
//app_logs.info("pValue : " + pValue.toString());
paramName = "";
paramValue = "";
}
}
}

Problem with reading textfiles with scanner in Java and ArrayLists

I'm having a problem where I read a textfile named "songs.txt" with Scanner in a function called loadFiles() which every line is:
Music ID # Song Name # Release Date
And with this I create a Song object, and then store said object in a ArrayList. After reading the file, I clone this ArrayList so I can return a ArrayList with the songs read and clear the first ArrayList to prevent the cases where for exemple:
(PS: I use the ArrayLists as global variables)
songs.txt has this structure:
1oYYd2gnWZYrt89EBXdFiO#Message In A Bottle#1979
7zxc7dmd82nd92nskDInds#Sweet Child of Mine#1980
And the loadFiles() is called 2 times, the ArrayList would have a size of 4 instead of 2 as it should be. So that's why after songs.txt is read I copy the arrayList and then clear the first ArrayList that way the ArrayList that's returned only has the size of 2.
This is my code:
package pt.ulusofona.aed.deisiRockstar2021;
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static ArrayList < Song > teste6 = new ArrayList < > ();
public static ArrayList < Song > getSongsArray = new ArrayList < > ();
public static ArrayList < Artista > testeSongArtists = new ArrayList < > ();
public static ParseInfo parseInfoSongsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsArtistsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsDetailsTxT = new ParseInfo(0, 0);
public static void main(String[] args) throws IOException {
ArrayList < Song > teste7 = new ArrayList < Song > ();
loadFiles();
loadFiles();
teste7 = getSongs();
ParseInfo teste8 = getParseInfo("songs.txt");
System.out.println("\n----------------------TESTE DO MAIN----------------------");
System.out.println(teste7.toString());
System.out.println(teste8.toString());
System.out.println(getSongsArray.size());
}
public static void loadFiles() throws IOException {
//Aqui lê-se o ficheiro songs.txt
System.out.println("----------------------LEITURA DO FICHEIRO songs.txt------------");
String nomeFicheiro = "songs.txt";
try {
File ficheiro = new File(nomeFicheiro);
FileInputStream fis = new FileInputStream(ficheiro);
Scanner leitorFicheiro = new Scanner(fis);
while (leitorFicheiro.hasNextLine()) {
String linha = leitorFicheiro.nextLine();
String dados[] = linha.split("#");
if (dados.length != 3) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[2].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
//Meter para ignorar a acabar com espaço
parseInfoSongsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String nome = dados[1];
int anoLancamento = Integer.parseInt(dados[2]);
Song song = new Song(idTemaMusical, nome, null, anoLancamento, 0, false, 0, 0, 0, 0);
teste6.add(song);
}
leitorFicheiro.close();
getSongsArray = (ArrayList < Song > ) teste6.clone();
teste6.clear();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro + " nao foi encontrado.";
System.out.println(mensagem);
}
System.out.println(teste6.toString());
System.out.println("Ok: " + parseInfoSongsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_artists.txt------------");
//Aqui é lido o ficheiro song_artists.txt, mas falta ver se é preciso separar vários artistas com o mesmo ID para posições diferentes no ArrayList
String nomeFicheiro2 = "song_artists.txt";
try {
File song_artists = new File(nomeFicheiro2);
FileInputStream fis2 = new FileInputStream(song_artists);
Scanner leitorFicheiro2 = new Scanner(fis2);
while (leitorFicheiro2.hasNextLine()) {
String linha = leitorFicheiro2.nextLine();
String dados[] = linha.split("#");
if (dados.length != 2) {
parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsArtistsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String artista = dados[1];
Artista artista2 = new Artista(idTemaMusical, artista);
testeSongArtists.add(artista2);
}
leitorFicheiro2.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro2 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println(testeSongArtists.toString());
System.out.println("Ok: " + parseInfoSongsArtistsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_details.txt------------");
//Aqui lê-se o ficheiro song_details.txt
boolean letra = false;
ArrayList < Song > testeSongDetails = new ArrayList < Song > ();
String nomeFicheiro3 = "song_details.txt";
try {
File song_details = new File(nomeFicheiro3);
FileInputStream fis3 = new FileInputStream(song_details);
Scanner leitorFicheiro3 = new Scanner(fis3);
while (leitorFicheiro3.hasNextLine()) {
String linha = leitorFicheiro3.nextLine();
String dados[] = linha.split("#");
if (dados.length != 7) {
parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[3].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[4].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[5].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[6].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsDetailsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
//System.out.println(idTemaMusical);
int duracao = Integer.parseInt(dados[1]);
//System.out.println(duracao);
int letraExplicita = Integer.parseInt(dados[2]);
//System.out.println(letraExplicita);
if (letraExplicita == 0) {
letra = false;
} else {
letra = true;
}
//System.out.println(letra);
int populariedade = Integer.parseInt(dados[3]);
//System.out.println(populariedade);
double dancabilidade = Double.parseDouble(dados[4]);
//System.out.println(dancabilidade);
double vivacidade = Double.parseDouble(dados[5]);
//System.out.println(vivacidade);
double volumeMedio = Double.parseDouble(dados[6]);
//System.out.println(volumeMedio);
Song song = new Song(idTemaMusical, null, null, 0, duracao, letra, populariedade, dancabilidade, vivacidade, volumeMedio);
testeSongDetails.add(song);
}
leitorFicheiro3.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro3 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println("Ok: " + parseInfoSongsDetailsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED);
}
public static ArrayList < Song > getSongs() {
return getSongsArray;
}
public static ParseInfo getParseInfo(String fileName) {
if (fileName == "songs.txt") {
return parseInfoSongsTxT;
}
if (fileName == "song_artists.txt") {
return parseInfoSongsArtistsTxT;
}
if (fileName == "song_details.txt") {
return parseInfoSongsDetailsTxT;
}
return null;
}
}
The problem is that when I made a test to check the function where the ArrayList is returned to see the size of the ArrayList it always comes as 0.
I think it's because only the function the returns the ArrayList is tested so loadFiles() isn't executed so the ArrayListo never gets cloned and that makes the ArrayList that is returned stay the same.
I thought about calling loadFiles() inside getSongs() and that way I would guarantee that the ArrayList is cloned but that would make getSongs use "throws IOException" and since I have to respect the school's project guide and getSongs doesn't include "throws IOException" i can't put it there.
But the more I think about it, that doesn't even make sense because how can they test it with a file of their own and loadFiles() isn't executed?
I'm out of ideas how to solve this problem, any help is welcome thank you.

Replace characters with substring using a loop Java

I am trying to replace each instance of what is between two brackets using a loop and an array. array1a and array1b are the indices of where the brackets open and close. I want to get the number between the two brackets and increment it by one and replace the value currently there, but as the string text is currently a list (such as "list item (0) list item (10) list item (1023)" I want to use a loop to increment the value of each rather than to set all the values within brackets to the same value. I hope this makes sense!
String text = myString.getText();
for (int x = 0; x < 10; x++) {
array2[x] = text.substring(array1a[x], array1b[x]);
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
String text2 = text.replaceAll("\\(.*\\)", array3[x]);
myString.setText(text2);
}
Full Code:
public class CreateVideoList extends JFrame implements ActionListener {
JButton play = new JButton("Play Playlist");
JButton addVideo = new JButton("Add Video");
TextArea playlist = new TextArea(6, 50);
JTextField videoNo = new JTextField(2);
private int x = 0;
#Override
public void actionPerformed(ActionEvent e) {
String key = videoNo.getText();
String name = VideoData.getName(key);
String director = VideoData.getDirector(key);
Integer playCount = VideoData.getPlayCount(key);
String text = playlist.getText();
String rating = CheckVideos.stars(VideoData.getRating(key));
String output = name + " - " + director + "\nRating: "
+ rating
+ "\nPlay Count: " + playCount;
String newItem = key + " " + name + " - " + director + " ("
+ playCount + ") " + "\n";
String addToList = "";
String[] array3 = new String[100];
if ("Add Video".equals(e.getActionCommand())) {
if (Character.isDigit(text.charAt(0)) == false) {
playlist.setText("");
}
if (addToList.indexOf(key) == -1) {
addToList += addToList + newItem;
playlist.append(addToList);
array3[x] = key;
x++;
} else if (addToList.indexOf(key) != -1) {
JOptionPane.showMessageDialog(CreateVideoList.this,
"This video is already in the playlist. Please select a"
+ " different video.", "Add to playlist error", JOptionPane.INFORMATION_MESSAGE);
}
}
if ("Play Playlist".equals(e.getActionCommand())) {
Integer length = (text.length());
int counta = 0;
Integer[] array1a = new Integer[100];
Integer[] array1b = new Integer[100];
String strPlayCount = "";
for (x = 0; x < length; x++) {
if (text.charAt(x) == '(') {
counta++;
array1a[counta - 1] = x;
array1a[counta - 1] = array1a[counta - 1] + 1;
}
if (text.charAt(x) == ')') {
array1b[counta - 1] = x;
array1b[counta - 1] = array1b[counta - 1];
}
}
String[] array2 = new String[counta];
String[] array4 = new String[100];
for (int y = 0; y < counta; y++) {
array2[y] = text.substring(array1a[y], array1b[y]);
array2[y] = array2[y] + 1;
playCount = Integer.parseInt(array2[y]);
array4[y] = "(" + array2[y] + ")";
String text2 = text.replaceAll("\\(.*\\)", array4[y]);
playlist.setText(text2);
}
}
}
Replace
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
with
Integer n = Integer.parseInt(array2[x]) + 1;
array3[x] = "(" + n.toString() + ")";

return array from inside an if,for statement

I am building a tag reader for inventory purpose. Using the for loop to iterate through the tags to count/total the ids. I get an error on my return line "tagsFound cannot be resolved into a variable". How do i use the variable inside the for loop and then access it outside the loop?
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
for (int i=0; i<tagList.length; i++) {
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
String[] tagsFound;
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
String[] tagsFound = new String[tagList.length];
for (int i=0; i<tagList.length; i++) {
tagsFound = "";
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
the returned array will have empty strings in the positions where the tag does not satisfy the criteria.

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.

Categories

Resources