0

I'm new to Java and i was using python and coding is different for me. I'm trying to make a string count with java , I have a problem when I execute it doesn't update the values of my json file it creates another textual in the subdirectory here is my code:

package sender;
import java.util.Iterator;
import java.util.Scanner; // import the Scanner class

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;
public class contar {

    public static void main(String[] args) throws ParseException, IOException {
        Scanner myObj = new Scanner(System.in);
        String userName;
        char[] cadena;
        char caracter;
        // Enter username and press Enter
        System.out.println("Enter username"); 
        userName = myObj.nextLine();   
        cadena = userName.toCharArray();     
        boolean[] yaEstaElCaracter = new boolean[Character.MAX_VALUE];
        int[] cuantasVeces = new int[Character.MAX_VALUE];

        for(int i =0;i<cadena.length;i++){
            caracter = cadena[i];
            System.out.println(caracter);
            if(cadena[i]==caracter){
                cuantasVeces[caracter]++;
            }
            yaEstaElCaracter[caracter] = true;
        }//Fin Para
        //Crea el json
        Object a;
        Object b;
        JSONObject jsd = new JSONObject();  
        jsd.put("listado","2");
        JSONArray list = new JSONArray();
        JSONObject obj = new JSONObject();
        for(int i = 0; i < yaEstaElCaracter.length; i++){
            if(yaEstaElCaracter[i]) {
                a= (char) i;
                b = cuantasVeces[i];
                //JSONObject jsd = new JSONObject();   
                /*jsd.put("listado","2");
                JSONArray list = new JSONArray();
                JSONObject obj = new JSONObject();*/
                obj.put((char) i,cuantasVeces[i] );
                
                
                
                
                System.out.println((char) i +" "+cuantasVeces[i]+" veces.");
        
            }
        }
        list.add(obj);
        jsd.put("frecuencias", list);
        
        
        File l = new File("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea");
        
        String[] bus = l.list();
        
        if (bus == null || bus.length == 0) {
            System.out.println("No hay elementos dentro de la carpeta actual");

            try (FileWriter file = new FileWriter("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json")){
                file.write(jsd.toString());
                file.flush();
                file.close();
                
            }catch(Exception e) {}
        }else {
            JSONParser jsonParser = new JSONParser();
            
            try (FileReader reader = new FileReader("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json"))
            {
                
                Object abc = jsonParser.parse(reader);
     
                JSONObject letras = (JSONObject) abc;
              
                
                JSONArray lang = (JSONArray) letras.get("frecuencias");
                
               
               for (int k = 0; k < lang.size(); k++) {
                    System.out.println("The " + k + " element of the array: " + lang.get(k));
                }
                Iterator k = lang.iterator();
     
                JSONObject jsonObject = new JSONObject(contents.trim());
                Iterator<String> keys = jsonObject.keys();

                while(keys.hasNext()) {
                    String key = keys.next();
                    if (jsonObject.get(key) instanceof JSONObject) {
                          JSONArray     
                    }
                }
                while (k.hasNext()) {
                    JSONObject innerObj = (JSONObject) k.next();
                    for (int i = 0; i < innerObj.size(); i++) {
                        System.out.println(i);
                    }
                    //System.out.println(innerObj.get(cadena.toString()));
                    
                }

                
                //Iterate over employee array
                //employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );
     
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            
            
            
            
            

        }
       
        }

}

This is my output:

{"listado":"2","frecuencias":[{" ":6,"a":4,"c":2,"d":2,"e":3,"g":1,"i":4,"m":3,"o":5,"p":1,"q":1,"r":2,"s":1,"t":1,"u":1,"y":1}]}{"a":6,c":2,"d":2,"e":3,} <---- I don't need this just update it
4
  • So, you are trying to store a list, and then retrieve it, update it, and store the new value again every time you run the script? Commented Jun 23, 2021 at 2:10
  • Yes , that's exactly what i'm trying to do Commented Jun 23, 2021 at 2:11
  • "creates another textual in the subdirectory": what does this mean? Commented Jun 23, 2021 at 2:12
  • That the report is like this {"listado":"2","frecuencias":[{" ":6,"a":4,"c":2,"d":2,"e":3,"g":1,"i":4,"m":3,"o":5,"p":1,"q":1,"r":2,"s":1,"t":1,"u":1,"y":1}]}--->{"a":6,c":2,"d":2,"e":3,}<----- This is what it creates and no updates the first values Commented Jun 23, 2021 at 2:13

2 Answers 2

1

First you need to fix this catch(Exception e) {}. If you hide or don't do anything with an exception then you will have no idea what has broken and why. Also, you only ever write to the file if bus == null or if bus.length == 0, is that correct? And then you only ever write your file to "C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json" is that path correct?

Edit your code to include some debugging and to show the error message:

if (bus == null || bus.length == 0) {
    System.out.println("No hay elementos dentro de la carpeta actual");

    try (FileWriter file = new FileWriter("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json")){
        //Print a message to check if your code ever for here
        System.out.println("Attempting to write the file");
        file.write(jsd.toString());
        file.flush();
        //Print a success message
        System.out.println("The file was successfully written to");       
    }
    catch(Exception e) {
        //Print the error to the console
        e.printStackTrace();
    }
}

Now you will be able to see if your code even got as far as writing to the file, and why it failed.

If you are still stuck then you need to update your question to include more information, including debugging details.

Sign up to request clarification or add additional context in comments.

Comments

1

First, what is contents in JSONObject jsonObject = new JSONObject(contents.trim());? I'm pretty sure you're referencing a variable above that you changed the name of at some point, because I don't see it anywhere else in this code.

Iterator k = lang.iterator();
     
                JSONObject jsonObject = new JSONObject(contents.trim());
                Iterator<String> keys = jsonObject.keys();

                while(keys.hasNext()) {
                    String key = keys.next();
                    if (jsonObject.get(key) instanceof JSONObject) {
                          JSONArray     
                    }
                }
                while (k.hasNext()) {
                    JSONObject innerObj = (JSONObject) k.next();
                    for (int i = 0; i < innerObj.size(); i++) {
                        System.out.println(i);
                    }
                    //System.out.println(innerObj.get(cadena.toString()));
                    
                }

Somewhere in here you're missing a call to jsd. I haven't run the script, but just reading it over, what I see is that you check to see if the file you are looking for exists, and if it doesn't you create the file using the data you have parsed into the object jsd. But if it does exists, you never do that. You seem to correctly open the file, read it into the buffer, and then ... you read that file back into the same file? Actually, you don't seem to do anything with it.

So I think that's where your issue is.

Two things to help:

  1. Like sorifiend alludes to, use your catchs better. Put some sort of println or message for each one that lets you know where the error occured, what type it is, and then, yeah print the stack trace.
  2. I suggest you go through and write comments about what need to get done, and about each step that's being completed. Lean towards the side of being overly explicit. Even write a comment for each line. This way, when you are looking through your code, you'll notice when you aren't doing something important (like writing to the file).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.