Класс Java: как создать класс, который возвращает строковый параметр, но также может использоваться в качестве точки входа для приложения? - PullRequest
0 голосов
/ 31 мая 2018

Следуя разделу «ТРУБА С СТРОКАМИ» этого руководства: http://www.jonathanbeard.io/tutorials/CtoJava

Я хочу изменить код StreamTest, чтобы я мог сохранить данные в переменную и передать их в другой класс.

Я пытался это сделать (см. Ниже), но когда я запускаю java -cp.StreamTest из учебного пособия я получаю следующее:

Основной метод не найден в классе StreamTest, определите основной метод как: public static void main (String [] args)

Это имеет смысл, я думаю, но я застрял на том, как подойти к этому сейчас.

Основная идея заключается в том, что я хочу иметь возможность получать данные из кода c, поместите его в переменную pass (я думаю, через код StreamTest), а затем передайте эту переменную моему классу mainLaptop

import java.io.BufferedInputStream; 
import java.io.IOException;
import java.io.InputStream;

public class StreamTest
{
private static final int buffer = 4096;
public static String main(String [] args, String pass)
{

    InputStream is = null;
    BufferedInputStream bis = null;
    try
    {
        bis = new BufferedInputStream(System.in,buffer);
        StringBuilder sb = new StringBuilder();
        sb.append((char)bis.read());
        while(bis.available() > 0)
        {
            sb.append((char)bis.read());
        }

        System.out.println("JAVA SIDE: "+sb.toString());
        pass=sb.toString();
        bis.close();

    }
    catch(IOException ex){}
    finally{}
    //return pass;
    return pass;

}
}

Вот основной класс, в который я хочу передать данные

public class mainLaptop 
{

public static void main(String arg) throws Exception 
{   
    //Timing out? change the IP!
    String ip="192.168.137.127";
    String Pi1Q1="Leonardo";
    String Pi1Q2="Raphael";
    String Pi2Q3="Donatello";
    String Pi2Q4="Michelangelo";
    String pass=arg;
    //pass= StreamTest.main(pass);

    Send.send(ip, Pi1Q1, pass);
    Send.send(ip, Pi1Q2, pass);
    Send.send(ip, Pi2Q3, pass);
    Send.send(ip, Pi2Q4, pass);

/*  Recv.recv(ip, Pi1Q1);
    Recv.recv(ip, Pi1Q2);
    Recv.recv(ip, Pi2Q3);
    Recv.recv(ip, Pi2Q4);*/
}
}

Вот немодифицированный StreamTest, который работает

import java.io.BufferedInputStream; 
import java.io.IOException;
import java.io.InputStream;

public class StreamTest
   {
    private static final int buffer = 4096;

   public static void main(String[] args) throws Exception 
  {   
    String pass=null;
    InputStream is = null;
    BufferedInputStream bis = null;
    try
    {
        bis = new BufferedInputStream(System.in,buffer);
        StringBuilder sb = new StringBuilder();
        //sb.append((char)bis.read());
        while(bis.available() > 0){
            sb.append((char)bis.read());
        }
        pass = sb.toString();
        System.out.println("JAVA SIDE: "+sb.toString());
        bis.close();
    }
    catch(IOException ex)
    {

    }

    finally
    {


    }

  //  mainLaptop.main(pass);

}

Вот код c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>

#define DEBUG 0
#define BUFFER 4096

//open ap.txt for text input
static const char* exFile = "ap.txt";
static char inputBuffer[BUFFER];

int main(int argc, const char** argv)
{
   FILE *fp = fopen(exFile,"r");
   /*check and see if the pointer is null in otherwords see if the memory 
   location refered to by fp is set...no memory location should be zero 
   if you want to reference it   
   Here are some good ways to do this other than the way I did it below:
   if(!fp) {do error}
   if(fp == NULL) {do error}
   and then there's the way I did it below
   */

   if(fp == 0){
      fprintf(stderr,"Null pointer exception, check file name.\n");
      exit(-1);
   }

   //check and see if an error occured during open
   const int err = ferror(fp);
   if(err != 0){
      /*
     void perror(const char* err)
     returns specific error message to string attached.

     */
  const char* errMessage = strcat("Something bad happened while opening 
  file ",exFile);
  perror(errMessage);
   }
     #if (DEBUG == 1)   
    else
    {
      fprintf(stderr,"Success opening file!!\n");
    }  
    #endif




setbuf(fp,inputBuffer); //set a buffer for input

uint64_t *num = (uint64_t*) malloc(sizeof(uint64_t));
uint64_t total = 0;
uint64_t n = 0;

//test for eof
/*
feof(*fp) - returns a boolean true if at end of file and false otherwise
*/

while(!feof(fp)){
//fscanf returns the number of items it converted using %llu, if it's not 
 equal to 1 we don't want to continue
   if(fscanf(fp,"%"PRIu64"",num)!=1)
  break; //you could do a lot of stuff here as far as error handling but 
basically something bad has happened
   total+= *num; //add to total the value at memory location num
   n++;
    #if (DEBUG == 1)   
    fprintf(stderr,"line number %"PRIu64"\n",n);
    #endif 
    }

    free(num);

const double average = (double) total / (double) n;
//close the inputfile
fclose(fp);

//declare our outputfile, use a pipe in this case to a java process
//we open a java process for this process to pipe to, also it is 
//technically a bi-directional pipe so we can use any of the modifiers
//like r/w/r+/etc
static const char* outFile = "java -cp . StreamTest";

FILE *fp_out = popen(outFile,"w");
//setbuf(fp_out,outputBuffer);

fprintf(fp_out,"Total: %"PRIu64", Integers: %"PRIu64", Average: 
%.4f\n",total,n,average);



/*
int fflush(*fp) pushes any data in the buffer to be written
the return value returns 0 if successful or !=0 if an error 
occurs....remember return values in C often equal exceptions

*/   
   fflush(fp_out);

/*

int 

 */
    fclose(fp_out);

   return 1;
}

Вот файл make

CC ?=gcc
JCC ?= javac
FLAGS ?= -Wall -O2
JFLAGS ?= -g -verbose

all: c_app StreamTest

c_app: c_app.c
    $(CC) $(FLAGS) -o c_app c_app.c

StreamTest: StreamTest.java
    $(JCC) $(JFLAGS) StreamTest.java $(LIBS)

clean:
    rm -f c_app StreamTest.class

Файл ap.text - это просто набор чисел

Я обновил свой код StreamTest и запустил его через eclipse, но у меня получилось

JAVA SIDE: 
 [x] Sent ''Leonardo
 [x] Sent ''Raphael
 [x] Sent ''Donatello
 [x] Sent ''Michelangelo

вместо

JAVA SIDE: 
 [x] Sent 'Total: 4953, Integers: 1000, Average: 4.9530'Leonardo
 [x] Sent 'Total: 4953, Integers: 1000, Average: 4.9530'Raphael
 [x] Sent 'Total: 4953, Integers: 1000, Average: 4.9530'Donatello
 [x] Sent 'Total: 4953, Integers: 1000, Average: 4.9530'Michelangelo

Обновлен StreamTest

import java.io.BufferedInputStream; 
import java.io.IOException;
import java.io.InputStream;

public class StreamTest
{
private static final int buffer = 4096;

public static void main(String[] args) throws Exception 
{
    String pass=null;
    InputStream is = null;
    BufferedInputStream bis = null;
    try
    {
        bis = new BufferedInputStream(System.in,buffer);
        StringBuilder sb = new StringBuilder();
        //sb.append((char)bis.read());
        while(bis.available() > 0){
            sb.append((char)bis.read());
        }
        pass = sb.toString();
        System.out.println("JAVA SIDE: "+pass);
        bis.close();
    }
    catch(IOException ex)
    {

    }

    finally
    {


    }
    //pass = "hi";
    mainLaptop.main(pass);

}    
}

1 Ответ

0 голосов
/ 31 мая 2018

Вы все неправильно поняли ... вы запускаете

java -cp

Так что это пытается запустить ваше приложение, отсюда и ошибка,что он не может найти метод Main, потому что Java ищет метод Main при попытке запустить приложение ...

Если вы хотите сохранить данные, просто передайте данные в команду следующим образом:

java -cp.класс "строка, которую вы хотите"

А затем в основном методе у вас есть "Строковые аргументы []", которые читаются из этого:)

EDITED

@ Джас Бадди, что ты делаешь ???Как вы можете иметь два основных метода ....?записка StreamTest использует только mainLaptop ....

public class mainLaptop 
{

public static void main(String arg) throws Exception 
{   
    //Timing out? change the IP!
    String ip="192.168.137.127";
    String Pi1Q1="Leonardo";
    String Pi1Q2="Raphael";
    String Pi2Q3="Donatello";
    String Pi2Q4="Michelangelo";
    String pass=arg[0]; // reads the argument you pass from command line or eclipse
    //pass= StreamTest.main(pass);

    Send.send(ip, Pi1Q1, pass);
    Send.send(ip, Pi1Q2, pass);
    Send.send(ip, Pi2Q3, pass);
    Send.send(ip, Pi2Q4, pass);

/*  Recv.recv(ip, Pi1Q1);
    Recv.recv(ip, Pi1Q2);
    Recv.recv(ip, Pi2Q3);
    Recv.recv(ip, Pi2Q4);*/
}
}

ЕСЛИ вы запускаете его из eclipse Нажмите правой кнопкой мыши на запуск -> Выполнить настройку -> Аргументы enter image description here

Вывод будет "teenagemutant", потому что мы взяли только args [0], если вы хотите другие значения, тогда arg 1 , args 2 ...

если вы хотите запустить его в командной строке, тогда enter image description here

...