Problem with reading textfiles with scanner in Java and ArrayLists - java

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.

Related

How to open java,python,other files in a JEditorPane

So I was wondering how I can actively change the color of keywords in the java text pane. I understand a document listener is will have to be used, but at the moment it doesn't seem to be working, in fact putting it in the document listener leads to me not being able to properly open a file or color at all. So how can I actively call a method that changes color of keywords in java. This is the code that will search for keywords and it works when I open files, just not actively.
public void findKeyWords(String directory) throws FileNotFoundException
{
final StyleContext cont = StyleContext.getDefaultStyleContext();
final AttributeSet jKeyWord = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.RED);
final AttributeSet jOperator = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.MAGENTA);
final AttributeSet jtypes = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.CYAN);
ArrayList<String> words = loadKeyWords(directory);
for (String line : words)
{
searchJava(line,jKeyWord);
}
ArrayList<String> operators = loadOperators(directory);
for (String line : operators)
{
searchJava(line, jOperator);
}
ArrayList<String> types1 = loadTypes(directory);
for (String line : types1)
{
searchJava(line, jtypes);
}
}
private ArrayList<String> loadKeyWords(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/keywords.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(scan.next() + " ");
}
scan.close();
return javaWords;
}
private ArrayList<String> loadOperators(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/operators.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(scan.next());
}
scan.close();
return javaWords;
}
private ArrayList<String> loadTypes(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/types.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(" " + scan.next());
}
scan.close();
return javaWords;
}
public void searchJava(String wordToSearch, AttributeSet javaAttr)
{
final AttributeSet attr = javaAttr;
Document text = textArea.getDocument();
int m;
int t;
int total = 0;
for (String line : textArea.getText().split("\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
total += line.length() + 1;
}
continue;
}
try{
text.remove(total + m, wordToSearch.length());
text.insertString(total + m, wordToSearch, attr);
}catch(BadLocationException ex)
{}
while(true)
{
m = line.indexOf(wordToSearch, m + 1 );
if (m == -1)
{
break;
}
try
{
text.remove(total + m, wordToSearch.length());
text.insertString(total + m, wordToSearch, attr);
}catch(BadLocationException e)
{
}
}
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
JOptionPane.showMessageDialog(null, "Eric You Troll" );
total += line.length() + 1;
}
}
}

Error message for StorageResource type

I've been trying to work on this problem for a while now but to no avail. When I run the code I get this error message: incompatible types: edu.duke.StorageResource cannot be converted to java.lang.String on line String geneList = FMG.storeAll(dna);. Does this mean I'm trying to make edu.duke object work with a java.lang.String type object? What would we go about resolving this issue?
Here's my code so far:
package coursera_java_duke;
import java.io.*;
import edu.duke.FileResource;
import edu.duke.StorageResource;
import edu.duke.DirectoryResource;
public class FindMultiGenes5 {
public int findStopIndex(String dna, int index) {
int stop1 = dna.indexOf("TGA", index);
if (stop1 == -1 || (stop1 - index) % 3 != 0) {
stop1 = dna.length();
}
int stop2 = dna.indexOf("TAA", index);
if (stop2 == -1 || (stop2 - index) % 3 != 0) {
stop2 = dna.length();
}
int stop3 = dna.indexOf("TAG", index);
if (stop3 == -1 || (stop3 - index) % 3 != 0) {
stop3 = dna.length();
}
return Math.min(stop1, Math.min(stop2, stop3));
}
public StorageResource storeAll(String dna) {
//CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCAdna = "CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCA";
String geneAL = new String();
String sequence = dna.toUpperCase();
StorageResource store = new StorageResource();
int index = 0;
while (true) {
index = sequence.indexOf("ATG", index);
if (index == -1)
break;
int stop = findStopIndex(sequence, index + 3);
if (stop != sequence.length()) {
String gene = dna.substring(index, stop + 3);
store.add(gene);
//index = sequence.substring(index, stop + 3).length();
index = stop + 3; // start at the end of the stop codon
}else{ index = index + 3;
}
}
return store;//System.out.println(sequence);
}
public void testStorageFinder() {
DirectoryResource dr = new DirectoryResource();
StorageResource dnaStore = new StorageResource();
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
String s = fr.asString();
dnaStore = storeAll(s);
printGenes(dnaStore);
}
System.out.println("size = " + dnaStore.size());
}
public String readStrFromFile(){
FileResource readFile = new FileResource();
String DNA = readFile.asString();
//System.out.println("DNA: " + DNA);
return DNA;
}//end readStrFromFile() method;
public float calCGRatio(String gene){
gene = gene.toUpperCase();
int len = gene.length();
int CGCount = 0;
for(int i=0; i<len; i++){
if(gene.charAt(i) == 'C' || gene.charAt(i) == 'G')
CGCount++;
}//end for loop
System.out.println("CGCount " + CGCount + " Length: " + len + " Ratio: " + (float)CGCount/len);
return (float)CGCount/len;
}//end of calCGRatio() method;
public void printGenes(StorageResource sr){
//create a FindMultiGenesFile object FMG
FindMultiGenes5 FMG = new FindMultiGenes5();
//read a DNA sequence from file
String dna = FMG.readStrFromFile();
String geneList = FMG.storeAll(dna);
//store all genes into a document
StorageResource dnaStore = new StorageResource();
System.out.println("\n There are " + geneList.size() + " genes. ");
int longerthan60 = 0;
int CGGreaterthan35 = 0;
for(int i=0; i<geneList.size(); i++){
if(!dnaStore.contains(geneList.get(i)))
dnaStore.add(geneList.get(i));
if(geneList.get(i).length() > 60) longerthan60++;
if(FMG.calCGRatio(geneList.get(i)) > 0.35) CGGreaterthan35++;
}
System.out.println("dnaStore.size: " + dnaStore.size());
System.out.println("\n There are " + dnaStore.size() + " genes. ");
System.out.println("There are " + longerthan60 + " genes longer than 60.");
System.out.println("There are " + CGGreaterthan35 + " genes with CG ratio greater than 0.35.");
}//end main();
}
I found your post as I am also doing a similar course at Duke using those edu.duke libraries.
When I get that error message it is because I'm using the wrong method to access it.
Try FMD.data() to get an iterable of all of the gene strings.

Using scanner to read file and group data

I'm using scanner to read file and group data , ive done some work but facing problem when im tring to deal with
The data sets is this.
You can see a example here, that explain everything.
What i ve done is this :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class TextScanner {
// static File f = new File("nrp1.txt");
public static void main(String[] args) throws FileNotFoundException {
TextScanner ts = new TextScanner();
ts.readfile();
}
public void readfile() throws FileNotFoundException {
FileInputStream fis = new FileInputStream("nrp1.txt");
Scanner scanner = new Scanner(fis);
int lineCount = 0;
String firstline = scanner.nextLine();
String secondline = scanner.nextLine();
String thirdline = scanner.nextLine();
String fourthline = scanner.nextLine();
String fifthline = scanner.nextLine();
String sixthline = scanner.nextLine();
String seventhline = scanner.nextLine();
String eighththline = scanner.nextLine();
List<Integer> intArrRIDA = new ArrayList<Integer>();
List<Integer> intArrRIDB = new ArrayList<Integer>();
int[] intRIDA = new int[Integer.parseInt(eighththline)];
int[] intRIDB = new int[Integer.parseInt(eighththline)];
List<Integer> intArrPOC = new ArrayList<Integer>();
List<Integer> intArrNORBC = new ArrayList<Integer>();
List<Integer> intArrRL = new ArrayList<Integer>();
String NoC="";
// COR arrays
thirdline.trim();
String[] CoR1 = thirdline.split(" ");
int[] intCoR1 = new int[CoR1.length];
for (int i = 0; i < intCoR1.length; i++) {
intCoR1[i] = Integer.parseInt(CoR1[i]);
}
fifthline.trim();
String[] CoR2 = fifthline.split(" ");
int[] intCoR2 = new int[CoR2.length];
for (int i = 0; i < intCoR2.length; i++) {
intCoR2[i] = Integer.parseInt(CoR2[i]);
}
seventhline.trim();
String[] CoR3 = seventhline.split(" ");
int[] intCoR3 = new int[CoR3.length];
for (int i = 0; i < intCoR3.length; i++) {
intCoR3[i] = Integer.parseInt(CoR3[i]);
}
while (scanner.hasNextLine()) {
lineCount++;
String line = scanner.nextLine().trim();
if (lineCount >= 1 && lineCount <= Integer.parseInt(eighththline)) {
// System.out.println("line: " + line);
String[] RID = line.split(" ");
for (int i = 0; i < 1; i++) {
intArrRIDA.add(Integer.parseInt(RID[0]));
intArrRIDB.add(Integer.parseInt(RID[1]));
// intRIDA[i] = Integer.parseInt(RID[0]);
// intRIDB[i] = Integer.parseInt(RID[1]);
// System.out.println("Id of RequirementA : " + intRIDA[i]);
// System.out.println("Id of RequirementB : " + intRIDB[i]);
}
}
if (lineCount == Integer.parseInt(eighththline)) {
NoC = scanner.nextLine();
}
//System.out.println("Number of Customer : " + NoC);
if (lineCount > Integer.parseInt(eighththline)) {
// System.out.println("line: " + line);
String[] Customers = line.split(" ");
System.out.println("Details of Customer : " +Arrays.toString(Customers) );
intArrPOC.add(Integer.parseInt(Customers[0]));
intArrNORBC.add(Integer.parseInt(Customers[1]));
for (int i = 0; i < 6; i++) {
intArrRL.add(Integer.parseInt(Customers[2]));
if (Customers[3] != null) {
intArrRL.add(Integer.parseInt(Customers[3]));
}
else if (Customers[4] != null) {
intArrRL.add(Integer.parseInt(Customers[4]));
}
else if (Customers[5] != null) {
intArrRL.add(Integer.parseInt(Customers[5]));
}
else if (Customers[6] != null) {
intArrRL.add(Integer.parseInt(Customers[6]));
}
else
continue;
}
}
}
System.out.println("Level of requirements, t: " + firstline);
System.out.println("Number of requirements in Level 1: " + secondline);
System.out.println("Costs of requirements in Level 1 : "
+ Arrays.toString(intCoR1));
System.out.println("Number of requirements in Level 2: " + fourthline);
System.out.println("Costs of requirements in Level 2 : "
+ Arrays.toString(intCoR2));
System.out.println("Number of requirements in Level 3: " + sixthline);
System.out.println("Costs of requirements in Level 3 : "
+ Arrays.toString(intCoR3));
System.out.println("Number of dependencies: " + eighththline);
// System.out.println("Id of RequirementA : " +
// Arrays.toString(intRIDA));
// System.out.println("Id of RequirementB : " +
// Arrays.toString(intRIDB));
System.out.println("Id of RequirementA : " + intArrRIDA);
System.out.println("Id of RequirementB : " + intArrRIDB);
System.out.println("Number of Customer : " + NoC);
System.out.println("Profit of Customer : " + intArrPOC);
System.out.println("Number of requests by Customer: " + intArrNORBC);
System.out.println("Requirements List : " + intArrRL);
}
private boolean isNumeric(String number) {
try {
Integer.parseInt(number);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
But as you can see :
for (int i = 0; i < 6; i++) {
intArrRL.add(Integer.parseInt(Customers[2]));
if (Customers[3] != null) {
intArrRL.add(Integer.parseInt(Customers[3]));
}
else if (Customers[4] != null) {
intArrRL.add(Integer.parseInt(Customers[4]));
}
else if (Customers[5] != null) {
intArrRL.add(Integer.parseInt(Customers[5]));
}
else if (Customers[6] != null) {
intArrRL.add(Integer.parseInt(Customers[6]));
}
else
continue;
}
This part is not correct ,and i need them to linked with Profit of Customer and Number of requests by Customer and when i implement further stuffs, i may able to find the corresponding Requirements List and the number of request by Profit of Customer...
I haven't started doing this method yet but that would be great if you can help me with this as well!
Thanks!

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.

Loading contact from phone book in J2ME

I implemented this code below in order to read contacts from the addressbook of the phone
The problem is, In a case when all the numbers in the phonebook are saved in the SIM it reads and displays the contacts for selection.
But in a case whereby any number is included on the phone memory, it gives an application error.(OutOfMemoryException)
What do I do (PS do not mind some System.out.println statements there. I used them for debugging)
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i] + " " + allContactLists[1]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute() error");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
// ----
// System.out.println("loadErr1");
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// System.out.println(contactList.getName());//--Phone Contacts or Sim Contacts
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME)
&& contactList.isSupportedField(Contact.TEL)) {
// ContactLst.append("Reading contacts...", null);
// System.out.println("sup1");
Enumeration items = contactList.items();
// System.out.println("sup2");
Vector telNumbers = new Vector();
telNames = new Vector();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
// System.out.println(telCount);
// System.out.println(nameCount);
// we're only interested in contacts with a phone number
// nameCount should always be > 0 since FORMATTED_NAME is
// mandatory
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone numbers
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
System.out.println(telNumber + " " + "tel");
// check if ATTR_MOBILE is supported
if (contactList.isSupportedAttribute(Contact.TEL, Contact.ATTR_MOBILE)) {
if ((telAttributes & Contact.ATTR_MOBILE) != 0) {
telNames.insertElementAt(telNames, i);
telNumbers.insertElementAt(telNumber, i);
} else {
telNumbers.addElement(telNumber);
telNames.addElement(telNames);
}
}
// else {
//// telNames.addElement(contactName);
// telNumbers.addElement(telNumber);
// }
System.out.println("telephone nos");
}
// Shorten names which are too long
shortenName(contactName, 20);
for (int i = 0; i <= telNumbers.size(); i++) {
System.out.println(contactName + " here " + telNames.size());
telNames.addElement(contactName);
System.out.println(telNames.elementAt(i) + " na " + i);
}
names = new String[telNames.size()];
for (int j = 0; j < names.length; j++) {
names[j] = (String) telNames.elementAt(j);
System.out.println(names[j] + "....");
}
// allTelNames.addElement(telNames);
System.out.println("cap :" + telNames.size() + " " + names.length);
// telNames.removeAllElements();
// telNumbers.removeAllElements();
}
}
available = true;
} else {
// ContactLst.append("Contact list required items not supported", null);
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}

Categories

Resources