Как я могу получить доступ к массиву, созданному в другой функции в main, не возвращая его?

Основная проблема заключается в том, можно ли разрешить переменную внутри экземпляра анонимного класса во время выполнения. Не обязательно делать переменную final, если она гарантирована, что переменная находится внутри области выполнения. Например, просмотрите две переменные _statusMessage и _statusTextView внутри метода updateStatus ().

public class WorkerService extends Service {

Worker _worker;
ExecutorService _executorService;
ScheduledExecutorService _scheduledStopService;

TextView _statusTextView;


@Override
public void onCreate() {
    _worker = new Worker(this);
    _worker.monitorGpsInBackground();

    // To get a thread pool service containing merely one thread
    _executorService = Executors.newSingleThreadExecutor();

    // schedule something to run in the future
    _scheduledStopService = Executors.newSingleThreadScheduledExecutor();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    ServiceRunnable runnable = new ServiceRunnable(this, startId);
    _executorService.execute(runnable);

    // the return value tells what the OS should
    // do if this service is killed for resource reasons
    // 1. START_STICKY: the OS restarts the service when resources become
    // available by passing a null intent to onStartCommand
    // 2. START_REDELIVER_INTENT: the OS restarts the service when resources
    // become available by passing the last intent that was passed to the
    // service before it was killed to onStartCommand
    // 3. START_NOT_STICKY: just wait for next call to startService, no
    // auto-restart
    return Service.START_NOT_STICKY;
}

@Override
public void onDestroy() {
    _worker.stopGpsMonitoring();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

class ServiceRunnable implements Runnable {

    WorkerService _theService;
    int _startId;
    String _statusMessage;

    public ServiceRunnable(WorkerService theService, int startId) {
        _theService = theService;
        _startId = startId;
    }

    @Override
    public void run() {

        _statusTextView = MyActivity.getActivityStatusView();

        // get most recently available location as a latitude /
        // longtitude
        Location location = _worker.getLocation();
        updateStatus("Starting");

        // convert lat/lng to a human-readable address
        String address = _worker.reverseGeocode(location);
        updateStatus("Reverse geocoding");

        // Write the location and address out to a file
        _worker.save(location, address, "ResponsiveUx.out");
        updateStatus("Done");

        DelayedStopRequest stopRequest = new DelayedStopRequest(_theService, _startId);

        // schedule a stopRequest after 10 seconds
        _theService._scheduledStopService.schedule(stopRequest, 10, TimeUnit.SECONDS);
    }

    void updateStatus(String message) {
        _statusMessage = message;

        if (_statusTextView != null) {
            _statusTextView.post(new Runnable() {

                @Override
                public void run() {
                    _statusTextView.setText(_statusMessage);

                }

            });
        }
    }

}
0
задан Professional Grammer 1 March 2019 в 05:54
поделиться

1 ответ

Вы можете объявить sorted [] как глобальную переменную вне main:

int sorted[3];
main()
{
  int a=20, b=15, c=22, sum;
 sum= sumsort(&a,&b,&c);
 printf("%d",sum);
 printf("%d", sorted[0]);
 printf("%d", sorted[1]);
 printf("%d", sorted[2]);

 }

И в своей функции вы можете использовать ее, как показано ниже:

 int sumsort(int *a, int *b, int *c) {

 int sum = *a + *b + *c;

 sorted[0] = *a; 
 sorted[1] = *b;
 sorted[2] = *c;
 for (int i = 0; i <= 2; i++) {

   if (sorted[0] > sorted[1]) 

   {
      int temp = sorted[1];
      sorted[1] = sorted[0];
      sorted[0] = temp;
   } // end if
   if (sorted[1] > sorted[2]) 
   {
      int temp2 = sorted[2];
      sorted[2] = sorted[1];
      sorted[1] = temp2;
   } // end if

} // end for

return sum;

} // end sumsort function

Возможно, вам придется проверьте логику сортировки.

Надеюсь, это поможет:)

0
ответ дан Gautham 1 March 2019 в 05:54
поделиться
Другие вопросы по тегам:

Похожие вопросы: