Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
1093 connectés 

  FORUM HardWare.fr
  Programmation
  Java

  réceptionner un matrice de c++ et la mettre dans une matrice en java

 

Sujet(s) à lire :
    - Visual C++
 

 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

réceptionner un matrice de c++ et la mettre dans une matrice en java

n°2208955
manel1989
Posté le 01-11-2013 à 16:36:20  profilanswer
 

salut tout le monde!
 
j'aimerais bien savoir comment on peut mettre une matrice qui est venu du code c++ dans le console java dans une matrice en java. En effet, j'envoie des paramètre à mon code c++ dépuis le code java, et la réception des résultat se fait au niveau du console java sous forme d'un text. moi je veux extraire de ce text une matrice que j'ai besoin plus loin dans le code , honnetement je sais pas comment le faire .
 
ci- dessous , je vous présente mon code java

Code :
  1. OutputStream out = null;
  2.      OutputStream err = null;
  3.      PipedInputStream pipedInput = new PipedInputStream();
  4.      PipedOutputStream pipedOutput = new PipedOutputStream(pipedInput);
  5.      Program prog = new Program("C:\\Users\\abdelhalim\\Desktop\\ExempleMMKP33.exe", System.out, System.err, pipedInput);
  6.         // TODO: Write pipedOutput from your favorite thread to send input to the program and finally close the stream.
  7.         // I will use a PrintWriter because we are working here with text and not binary data.
  8.         PrintWriter pw = new PrintWriter(pipedOutput);
  9.         // println outputs platform specific newline but pw.print("5\n" ) would also convert "\n" to platform specific newline.
  10.       
  11.       
  12.        res1= new int[n][m];
  13.         pw.println(m);
  14.         pw.println(n);
  15.         pw.println(m);
  16.         pw.println(n);
  17.       
  18.         for(int k=0; k<R.size();k++)
  19.         { 
  20.         pw.println(R.get(k));
  21.         }
  22.       
  23.         for(int k=0; k<C.size();k++)
  24.         {
  25.        
  26.         pw.println(C.get(k));
  27.         }
  28.         for(int k=0; k<B.size();k++)
  29.         {
  30.        
  31.         pw.println(B.get(k));
  32.         }
  33.         for(int k=0; k<Dr.size();k++)
  34.         {
  35.        
  36.         pw.println(Dr.get(k));
  37.         }
  38.         for(int k=0; k<Dc.size();k++)
  39.         {
  40.        
  41.         pw.println(Dc.get(k));
  42.         }
  43.         for(int k=0; k<Db.size();k++)
  44.         {
  45.        
  46.         pw.println(Db.get(k));
  47.         }
  48.         /*for(int k=0; k<n;k++)
  49.         {
  50.       for(int j=0; j<m;j++)
  51.       pw.println(GainMatrix[k][j]);
  52.      }*/
  53.         pw.println(n);
  54.         pw.println(m);
  55.         pw.println(m);
  56.         pw.println(m);
  57. pw.close();


   
et c'est ce que je reçoit dans le console:
 

Code :
  1. 0   0   0   0   1   0
  2.    0   0   0   0   0   1
  3.    0   1   0   0   0   0
  4.    0   0   0   1   0   0
  5.    0   0   0   0   1   0
  6.    0   0   1   0   0   0
  7. Initial
  8. propagators: 24
  9. branchers:   1
  10. Summary
  11. runtime:      1.735 (1735.000 ms)
  12. solutions:    48
  13. propagations: 1715
  14. nodes:        153
  15. failures:     29
  16. restarts:     0
  17. peak depth:   7
  18. peak memory:  13 KB


 
je veux mettre cette matrice dans un code java( matrice de type res1= new int[n][m]) après la reception et je sais pas comment faire  
 
avez vous une idée sur ça ??? merci beaucoup pour votre aide  
 


---------------
when there is a will there is a way
mood
Publicité
Posté le 01-11-2013 à 16:36:20  profilanswer
 

n°2208980
honrisse
Posté le 02-11-2013 à 07:12:03  profilanswer
 

Salut.
Si les dimensions de la matrice sont connues, je ferais un parsing de la sortie du programme C++.
Quelque chose comme ça :

Code :
  1. String parseText = "    0   0   0   0   1   0"+"\n"+
  2.        "0   0   0   0   0   1"+"\n"+
  3.        "0   1   0   0   0   0"+"\n"+
  4.        "0   0   0   1   0   0"+"\n"+
  5.        "0   0   0   0   1   0"+"\n"+
  6.        "0   0   1   0   0   0"+"\n"+
  7.     "Initial"+"\n"+
  8.     "propagators: 24"+"\n"+
  9.     "branchers:   1"+"\n"+
  10.     "Summary"+"\n"+
  11.     "runtime:      1.735 (1735.000 ms)"+"\n"+
  12.     "solutions:    48"+"\n"+
  13.     "propagations: 1715"+"\n"+
  14.     "nodes:        153"+"\n"+
  15.     "failures:     29"+"\n"+
  16.     "restarts:     0"+"\n"+
  17.     "peak depth:   7"+"\n"+
  18.     "peak memory:  13 KB";
  19.  // convert String into InputStream
  20.  InputStream is = new ByteArrayInputStream(parseText.getBytes());
  21.  // read it with BufferedReader
  22.  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  23.  String line;
  24.  try {
  25.   int nbLine = 6;
  26.   int nbCol = 6;
  27.   int cpt = 0;
  28.   int[][] mat = new int[nbLine][nbCol];
  29.   while ((line = br.readLine()) != null) {
  30.    if(cpt>=nbLine) break;
  31.           String[] split = line.trim().split("\\s+" );
  32.    try{
  33.     for(int i = 0; i<split.length && i<nbCol; i++){
  34.      mat[cpt][i] = Integer.parseInt(split[i]);
  35.     }
  36.              }
  37.              catch(NumberFormatException e){
  38.              }
  39.    cpt++;
  40.   }
  41.   System.out.println("Matrice :" );
  42.   for(int[] rows : mat){
  43.    for(int cel : rows){
  44.     System.out.print(cel + " " );
  45.    }
  46.    System.out.println();
  47.   }
  48.  } catch (IOException e) {
  49.   e.printStackTrace();
  50.  } finally {
  51.   try {
  52.    br.close();
  53.   } catch (IOException e) {
  54.    e.printStackTrace();
  55.   }
  56.  }

n°2209788
manel1989
Posté le 09-11-2013 à 03:24:05  profilanswer
 

honrisse: merci beaucoup pour votre réponse , normalement lorsque la réponse attendue du code c++ est venue  cette réponse doit etre placer dans le PipedInputStream nn?? si oui comment je peux la convertir vers un String pour l'exploiter plus tard dans le code ???
 
Merci beaucoup pour votre aide  
 

n°2209859
honrisse
Posté le 10-11-2013 à 16:31:45  profilanswer
 

Bonjour,
 
Je ne connais pas les PipedInputStream et il manque le code pour la classe Program pour y voir plus clair.
Comme le problème m'intéressait (appeler du code C++ à partir de Java et récupérer la sortie), pour m'entraîner j'ai essayé de faire un programme de test qui part sur le même principe.
Si modifier votre code ne vous dérange pas trop, vous pouvez essayer d'adapter le code suivant.
 
Code C++ : fait la transposition d'une matrice

Code :
  1. #include <iostream>
  2.  
  3. using std::cout;
  4. using std::cin;
  5. using std::endl;
  6.  
  7. int main (int argc, char*argv[])
  8. {
  9.     //Nb lignes matrice
  10.     int nbLine = 0;
  11.     cin >> nbLine;
  12.     //Nb colonnes matrice
  13.     int nbCol = 0;
  14.     cin >> nbCol;
  15.  
  16.     //Matrice initiale
  17.     int* mat = new int[nbLine*nbCol];
  18.     for(int i = 0; i<nbLine*nbCol; i++)
  19.     {
  20.         cin >> mat[i];
  21.     }
  22.  
  23.     //Matrice transposee
  24.     int* matTranspose = new int[nbLine*nbCol];
  25.     for(int i = 0; i<nbCol; i++)
  26.     {
  27.         for(int j = 0; j<nbLine; j++)
  28.         {
  29.             matTranspose[i*nbCol+j] = mat[j*nbCol+i];
  30.         }
  31.     }
  32.  
  33.     //Affichage matrice tranposee
  34.     for(int i = 0; i<nbCol; i++)
  35.     {
  36.         for(int j = 0; j<nbLine; j++)
  37.         {
  38.             cout<<matTranspose[i*nbCol+j]<<" ";
  39.         }
  40.         cout<<endl;
  41.     }
  42.     return 0;
  43. }


 
Code Java : appelle le programme C++ et récupère la sortie sous forme d'un String

Code :
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.io.OutputStreamWriter;
  8. import java.util.concurrent.Callable;
  9. import java.util.concurrent.ExecutionException;
  10. import java.util.concurrent.ExecutorService;
  11. import java.util.concurrent.Executors;
  12. import java.util.concurrent.Future;
  13.  
  14.  
  15. //Thread pour la lecture des differents flux
  16. class AfficheurDuFlux implements Callable<String> {
  17.  
  18.    private final InputStream inputStream;
  19.  
  20.    AfficheurDuFlux(InputStream inputStream) {
  21.        this.inputStream = inputStream;
  22.    }
  23.  
  24.    private BufferedReader getBufferedReader(InputStream is) {
  25.        return new BufferedReader(new InputStreamReader(is));
  26.    }
  27.  
  28.    @Override
  29.    public String call() {
  30.        StringBuilder sb = new StringBuilder();
  31.        BufferedReader br = getBufferedReader(inputStream);
  32.        String ligne = "";
  33.        try {
  34.            while ((ligne = br.readLine()) != null) {
  35.                sb.append(ligne + "\n" );
  36.            }
  37.        } catch (IOException e) {
  38.            e.printStackTrace();
  39.        }
  40.        
  41.        return sb.toString();
  42.    }
  43. }
  44.  
  45. public class Main {
  46.     public static void main(String[] args) {        
  47.         try {            
  48.             //Appel du programme C++ a partir de Java
  49.            ProcessBuilder pb = new ProcessBuilder("./Programme/MatTranspose.exe" );          
  50.            Process p = pb.start();            
  51.            
  52.            
  53.            //Creation de 2 threads pour lire les flux de sortie et derreur du programme C++
  54.            ExecutorService executor = Executors.newFixedThreadPool(2);
  55.            
  56.            Callable<String> callableFluxSortie = new AfficheurDuFlux(p.getInputStream());
  57.            Callable<String> callableFluxErreur = new AfficheurDuFlux(p.getErrorStream());
  58.            
  59.            Future<String> futureSortie = executor.submit(callableFluxSortie);
  60.            Future<String> futureErreur = executor.submit(callableFluxErreur);
  61.            executor.shutdown();
  62.            
  63.            OutputStream stdin = p.getOutputStream();
  64.            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
  65.            
  66.            //nb ligne matrice
  67.            writer.write("3" );
  68.            writer.newLine();
  69.            
  70.            //nb colonne matrice
  71.            writer.write("3" );
  72.            writer.newLine();
  73.            
  74.            //Matrice:
  75.            //[ 1 2 3
  76.            //  3 2 1
  77.            //  2 1 3]
  78.            
  79.            //remplissage de la matrice vers le prog C++
  80.            writer.write("1" ); writer.newLine();
  81.            writer.write("2" ); writer.newLine();
  82.            writer.write("3" ); writer.newLine();
  83.            
  84.            writer.write("3" ); writer.newLine();
  85.            writer.write("2" ); writer.newLine();
  86.            writer.write("1" ); writer.newLine();
  87.  
  88.            writer.write("2" ); writer.newLine();
  89.            writer.write("1" ); writer.newLine();
  90.            writer.write("3" ); writer.newLine();
  91.            
  92.            writer.flush();
  93.            writer.close();            
  94.            
  95.            
  96.            //Attente fin du programme C++
  97.            p.waitFor();
  98.            
  99.            try {
  100.                 System.out.println("\nFlux sortie : \n" + futureSortie.get());
  101.             } catch (ExecutionException e) {
  102.                 e.printStackTrace();
  103.             }
  104.            
  105.            try {
  106.                 System.out.println("\nFlux erreur : \n" + futureErreur.get());
  107.             } catch (ExecutionException e) {
  108.                 e.printStackTrace();
  109.             }
  110.  
  111.        } catch (IOException e) {
  112.            e.printStackTrace();
  113.        } catch (InterruptedException e) {
  114.            e.printStackTrace();
  115.        }
  116.     }
  117. }


 
Idéalement il faudrait aussi que p.getOutputStream() soit appelé à partir d'un thread et utiliser un pipe pour remplir les entrées du programme C++.


Message édité par honrisse le 10-11-2013 à 16:53:38
n°2209862
manel1989
Posté le 10-11-2013 à 17:41:41  profilanswer
 

merci beaucoup pour votre aide :)
 
si vous voulez savoir comment j'ai programmé la classe programme ok  
 

Code :
  1. package projetPFE;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.util.Scanner;
  6. class Program
  7. {
  8.     private final Process proc;
  9.     private final Thread out, err, in;
  10.    
  11.     public Program(String cmd, OutputStream pOut, OutputStream pErr, InputStream pIn) throws IOException
  12.     {
  13.         proc = Runtime.getRuntime().exec(cmd);
  14.        
  15.         out = new Transfert(proc.getInputStream(), pOut);
  16.         err = new Transfert(proc.getErrorStream(), pErr);
  17.         in = new Transfert(pIn, proc.getOutputStream());
  18.        
  19.         out.start();
  20.         err.start();
  21.         in.start();
  22.     }
  23.    
  24.     public void kill()
  25.     {
  26.         out.interrupt();
  27.         err.interrupt();
  28.         in.interrupt();
  29.        
  30.         proc.destroy();
  31.     }
  32. }
  33. class Transfert extends Thread
  34. {
  35.     private final InputStream in;
  36.     private final OutputStream out;
  37.    
  38.     public Transfert(InputStream in, OutputStream out)
  39.     {
  40.         this.in = in;
  41.         this.out = out;
  42.     }
  43.    
  44.     @Override
  45.     public void run()
  46.     {
  47.         Scanner sc = new Scanner(in);
  48.         try
  49.         {
  50.             while (sc.hasNextLine())
  51.             {
  52.                 out.write((sc.nextLine() + System.lineSeparator()).getBytes());
  53.                 out.flush();
  54.                
  55.                 if (isInterrupted())
  56.                     break;
  57.             }
  58.         }
  59.         catch (IOException e)
  60.         {
  61.             System.err.println(e);
  62.         }
  63.        
  64.         sc.close();
  65.     }
  66. }


 
je vais essayer de comprendre ta réponse merci beaucoup encore une fois


---------------
when there is a will there is a way
n°2209885
manel1989
Posté le 11-11-2013 à 01:33:51  profilanswer
 

Salut!
 
j'ai essayé votre code ( copier coller ) et sa marche très bien, mais le problème maintenant c'est d'adapter ce code par exemple à la place de :

Code :
  1. writer.write("3" );
  2.             writer.newLine();


 
j'ai mis juste ça

Code :
  1. int m=3;
  2. writer.write(m );
  3.             writer.newLine();


 
mais il m'envoie l'erreur suivante:

Code :
  1. R6010
  2. abort() has been called


 
est ce que c'est normale ça???? noramalement m c'est de type int donc il l'accepte non????
 
est l'affichage comme suit  
 

Code :
  1. Flux sortie :
  2. Flux erreur :


 
je suis très désolée pour le dérangement et merci beaucoup pour votre aide  
 
bonne nuit


---------------
when there is a will there is a way
n°2209888
honrisse
Posté le 11-11-2013 à 07:54:50  profilanswer
 

J'ai testé pour mon programme de test et il faut utiliser String.valueOf :

Code :
  1. int m = 3;
  2. writer.write(String.valueOf(m));
  3. writer.newLine();

n°2211235
manel1989
Posté le 21-11-2013 à 14:51:51  profilanswer
 

Salut
 
merci beaucoup pour votre aide l'autrefois  :)  
 
j'ai essayé d'appliquer le meme démarche pour cette sortie :

Code :
  1. MMKP
  2. {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}
  3. Initial
  4. propagators: 25
  5. branchers:   1
  6. Summary
  7. runtime:      0.003 (3.000 ms)
  8. solutions:    1
  9. propagations: 125
  10. nodes:        8
  11. failures:     1
  12. restarts:     0
  13. peak depth:   6
  14. peak memory:  10 KB
  15. Appuyez sur une touche pour continuer...


 
mais j'ai eu un problème au niveau de cette ligne :  

Code :
  1. {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}


 
comment je peux la fixer  
 
merci beaucoup pour votre aide


---------------
when there is a will there is a way
n°2211432
honrisse
Posté le 23-11-2013 à 10:16:56  profilanswer
 

Bonjour,
 
Si je comprend bien, vous voulez récupérer la suite de nombres entre les accolades :
 

Code :
  1. import java.io.BufferedReader;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. public class Main4 {
  9. public static void main(String[] args) {
  10.  String parseText = "    MMKP" + "\n" +
  11.      "{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}" + "\n" +
  12.      "Initial" + "\n" +
  13.      "propagators: 25" + "\n" +
  14.      "branchers:   1" + "\n" +
  15.      "Summary" + "\n" +
  16.      "runtime:      0.003 (3.000 ms)" + "\n" +
  17.      "solutions:    1" + "\n" +
  18.      "propagations: 125" + "\n" +
  19.      "nodes:        8" + "\n" +
  20.      "failures:     1" + "\n" +
  21.      "restarts:     0" + "\n" +
  22.      "peak depth:   6" + "\n" +
  23.      "peak memory:  10 KB" + "\n" +
  24.      "Appuyez sur une touche pour continuer...";
  25.  // convert String into InputStream
  26.  InputStream is = new ByteArrayInputStream(parseText.getBytes());
  27.  // read it with BufferedReader
  28.  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  29.  String line = null;
  30.  try {
  31.   List<Integer> listOfInt = new ArrayList<>();
  32.   while ((line = br.readLine()) != null) {
  33.    String txt = line.trim();
  34.    //Ligne de texte qui commence par { et se termine par }
  35.    if(txt.startsWith("{" ) && txt.endsWith("}" )) {
  36.     //On enleve les accolades (1er et dernier caractere) avec substring
  37.      //http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring%28int,%20int%29
  38.     //On garde les elements espaces par des virgules avec split
  39.     //http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29
  40.     String[] split = txt.substring(1, txt.length() - 1).split(",\\s" );
  41.     try{
  42.      for(String s : split) {
  43.       listOfInt.add(Integer.parseInt(s));
  44.      }
  45.                   }
  46.              catch(NumberFormatException e){
  47.               e.printStackTrace();
  48.              }
  49.    }       
  50.   }
  51.   System.out.println("Resultat :" );
  52.   for(int value : listOfInt){
  53.    System.out.print(value + ", " );
  54.   }
  55.   System.out.println();
  56.  } catch (IOException e) {
  57.   e.printStackTrace();
  58.  } finally {
  59.   try {
  60.    br.close();
  61.   } catch (IOException e) {
  62.    e.printStackTrace();
  63.   }
  64.  }
  65. }
  66. }


Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  Java

  réceptionner un matrice de c++ et la mettre dans une matrice en java

 

Sujets relatifs
[Java] Page HTML de mon programmeenvoyer tout un vecteur comme un paramètre de Java en C + +
Java's cool 4 - Proglet polyominos - problème ![Java] Liste chaînée - Pile
[Java] Aide pour un programmecomparer et mettre a jour 2 tables en SQL
Tracer d'une fonction de répartition sous javaenvoyer des paramètre d'une application java à une application c++
l'échange des données entre une application c++ et application javalancer une application c++ depuis une autre application codé en java
Plus de sujets relatifs à : réceptionner un matrice de c++ et la mettre dans une matrice en java


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR