Question

I'm generating a random number every 10 second and Storing and Updating the number every 10...

I'm generating a random number every 10 second and Storing and Updating the number every 10 second when I generate new number in UpdateInt method. However, In my main method when I called UpdateInt method it generate every 10 second new number but it doesn't update and store in the arraylist.

***I want the Runnable to be in the arraylist method. Not in main method. my goal is to send the arraylist that has the update number***

import java.util.ArrayList;

import java.util.Random;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class EverySecond {

public static int genrand() {

Random number = new Random();

//generate random number

int rand = number.nextInt(1000);

//return generated random number

return rand;

}

public static ArrayList<Integer> UpdateInt(){

ArrayList<Integer> Update = new ArrayList<Integer>();

Runnable helloRunnable = new Runnable() {

public void run() {

int CurrentNum = genrand(); //create a random number

System.out.println("generate number ==== " + CurrentNum);

Update.add(CurrentNum);//update it in array list

}

};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

//schedule thread for evry 10 seconds

executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);

return Update;

}

public static void main(String[] args) throws Exception {

ArrayList<Integer> getUpdate=UpdateInt();

for(int x=0;x<getUpdate.size();x++) {

System.out.println("Current Num = " + getUpdate.get(x));

}

}

}

Current Output:

generate number ==== 367

generate number ==== 944

It should be :

generate number ==== 367

Current Num = 367

generate number ==== 47

Current Num = 47

NOTE: ***I want the Runnable to be in the arraylist method. Not in main method. my goal is to send the arraylist that has the update number***

I should get the same number in main method when Ioop that I generated in UpdateInt method. Note: I want the Runnable() to be in arraylist method and return the arraylist that has the update number. I would apperciate any help.

Homework Answers

Answer #1

Hi,

Please find updated code below.

For this since we return a value we need a callable wrapped around in runnable.

runnable is required to run at every 10 seconds.

Callable is required to return updated array.

As demonstrated in program below.

Main.java :

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Main
{
public static void main(String[] args) throws Exception
{
  
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  
//schedule thread for evry 10 seconds
  
//executor.schedule(new sampleCallableExample(), 1, TimeUnit.MILLISECONDS);
executor.scheduleAtFixedRate(new sampleCallableExample(), 0, 10, TimeUnit.SECONDS);
System.out.println("array size:"+globals.Update.size());
for(int x=0;x<globals.Update.size();x++)
{
  
System.out.println("Current Num = " + globals.Update.get(x));
  
}
  
}
}

Kindly declare Update array as global variable: inside new class globals as shown below:

import java.util.ArrayList;
public class globals
{
public static ArrayList<Integer> Update = new ArrayList<Integer>();
  
}

sampleCallableExample.java :

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.Random;
class sampleCallableExample implements Runnable
{
public static int genrand()
{
Random number = new Random();
//generate random number
int rand = number.nextInt(1000);
//return generated random number
return rand;
}
public Object call() throws Exception
{
//ArrayList<Integer> Update = new ArrayList<Integer>();
int CurrentNum = genrand();
System.out.println("generate number ==== " + CurrentNum);
globals.Update.clear();
globals.Update.add(CurrentNum);
System.out.println("Number added");
return globals.Update;
}

// As seen run wraps call object
public void run()
{
try
{
Object o = call();
//System.out.println("Returned " + o);
}
catch (Exception e)
{
e.printStackTrace();
}
}

public sampleCallableExample()
{
try
{
run();
  
  
}
catch(Exception e)
{
}
  
}
  
}   

output attached: You can see current num and generated number updated.

Thanks,

kindly upvote.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
/* This program should check if the given integer number is prime. Reminder, an integer number...
/* This program should check if the given integer number is prime. Reminder, an integer number greater than 1 is prime if it divisible only by itself and by 1. In other words a prime number divided by any other natural number (besides 1 and itself) will have a non-zero remainder. Your task: Write a method called checkPrime(n) that will take an integer greater than 1 as an input, and return true if that integer is prime; otherwise, it should...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { flavor = s; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         System.out.println(pepper.getFlavor());     } } a. a class variable b. a constructor c. a local object variable d....
The following program creates a linked list which contains 5 links. Add a method called doubleValue()...
The following program creates a linked list which contains 5 links. Add a method called doubleValue() to the LinkedList class. The doubleValue() method must double the value of the number data field in each link. Add the required code to the main() method to call the doubleValue() method and display the revised list. public class Link { private int number; private Link next;      public Link(int x) { number = x; }    public void displayLink() { System.out.println("The number is:...
The following program creates a linked list which contains 5 links. Add a method called doubleValue()...
The following program creates a linked list which contains 5 links. Add a method called doubleValue() to the LinkedList class. The doubleValue() method must double the value of the number data field in each link. Add the required code to the main() method to call the doubleValue() method and display the revised list. public class Link { private int number; private Link next;      public Link(int x) { number = x; }    public void displayLink() { System.out.println("The number is:...
Write a method that returns the sum of all the elements in a specified column in...
Write a method that returns the sum of all the elements in a specified column in a 3 x 4 matrix using the following header: public static double sumColumn(double[][] m, int columnIndex) The program should be broken down into methods, menu-driven, and check for proper input, etc. The problem I'm having is I'm trying to get my menu to execute the runProgram method. I'm not sure what should be in the parentheses to direct choice "1" to the method. I'm...
Question: I am using three different ways to execute this program. I am a bit confused...
Question: I am using three different ways to execute this program. I am a bit confused on the time complexity for each one. Can someone explain the time complexity for each function in relation to the nanoseconds. import java.util.HashMap; import java.util.Map; public class twosums {       public static void main(String args[]) {               int[] numbers = new int[] {2,3,9,4,8};;        int target = 10;               long nano_begin1 = System.nanoTime();        int[]...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length();...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length(); for (int i = 0; i < array.length; i++) { if (array[i].length() < minLength) minLength = array[i].length(); } return minLength; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] strings = new String[50]; for (int i = 0; i < strings.length; i++) { System.out.print("Enter string " + (i + 1) + ": "); strings[i] = in.nextLine(); } System.out.println("Length of smallest...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT