I am trying to run the program, but it throws an exception, which I am not able to fix.
public class Multithread extends Thread {
static int [][]array1;
static int [][]array2;
static int [][]array3;
static final int i=10;
static final int j=10;
static final int k=10;
volatile int start;
volatile int end;
Multithread(int start,int end){
this.start=start;
this.end=end;
}
private static void multiplication() {
int processors=Runtime.getRuntime().availableProcessors();
int threadcount=processors>=i ? i:processors;
Thread [] t=new Thread[threadcount];
int [] idx= new int[threadcount+1];
for(int a=0;a<=threadcount;a++){
idx[a]=(a*i)/threadcount;
//System.out.println("idx:"+idx[a]);
}
for(int a=0;a<threadcount;a++){
t[a]=new Multithread(idx[a],idx[a+1]);
//thread 1=start 0 end 9, thread 2 = 9 end =19
t[a].start();
}
}
public static void main(String[] args) {
for(int a = 0; a < i; a++)
for(int b = 0; b < j; b++)
array1[a][b]= (int)(Math.random()*10);
for(int a=0;a<j;a++)
for(int b=0;b<k;b++)
array2[a][b]= (int)(Math.random()*10);
long starttime=System.nanoTime();
multiplication();
long endtime=System.nanoTime();
System.out.println("Total time taken is "+((endtime-starttime)/1000));
}
public void run(){
for(int a=start;a<end;a++){
for(int b=0;b<k;b++){
for(int c=0;c<j;c++){
array3[a][b]=(array3[a][b]+(array1[a][c]*array2[c][b]));
}
}
}
}
}
This code will give the execution time for the matrix in parallel programming. It gives me NullPointerException. I can't fix that. it gives the exception for the array1[a][b]. I tried resolving it, but could not.
You don't properly initialize your variables. Just initialize your 2d array to something, so you can later just pass reference.
array1 = blah blah //this is right
array1[a][b] //you are creating it like this everytime which is wrong.
Related
I have to insert the elements using three threads by creating three classes, namely Task1,Task2 and Task3. The values to be inserted into the array are 0,1,2,....299.
Override the run method in the threads. Three integer i,j, and k representing the number of elements each thread should append inside the given array.
Thread one should append 0 to i-1 inside the array,thread two should append i to i+j-1 inside the array,and the third thread should append i+j to 299 inide the array.
Threads one and two must run simultaneously, and the values of the threads one and two must be inserted inside the indices of the array from 0 to i+j-1 randomly.The third thread should start only after the first two threads have been executed completely.
In these code three task are given.
first task and second task start executing the thread at the same time and after completion of first two task then only third task start. If these situation getting correct then test() method return true.
public static final int[] threadArray = new int[300]; how I add random number into these array using Task1 Task2 and Task3 class.
Input :
80
130
90
Output :
True
import java.util.Scanner;
class Task1 extends Thread
{
static int a = 0;
static int beg = 0;
public void run()
{
for(int i=a;i<=beg;i++)
{
Solution.threadArray[i] = i;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Task2 extends Thread
{
static int a = 0;
static int beg = 0;
#Override
public void run()
{
// TODO Auto-generated method stub
for(int i=a;i<=beg;i++)
{
Solution.threadArray[i] = i;
}
}
}
class Task3 extends Thread
{
static int a = 0;
static int beg = 0;
public void run()
{
// TODO Auto-generated method stub
for(int i=a;i<=beg;i++)
{
Solution.threadArray[i] = i;
}
}
}
public class Solution
{
public static final int[] threadArray = new int[300];
public static volatile String i = 0+"";
public boolean test() throws InterruptedException
{
Task1 task1 = new Task1();
Task2 task2 = new Task2();
Task3 task3 = new Task3();
Thread task2Thread = new Thread(task2);
Thread task3Thread = new Thread(task3);
task1.start();
task2Thread.start();
task1.join();
task2Thread.join();
task3Thread.start();
int first = Task1.a+Task2.a;
int containsSecondThread = Task1.a;
String oneAndTwo = "";
String sizeOfTask1 = "";
for(int i=0;i<first;i++)
{
oneAndTwo += threadArray[i]+" ";
}
for(int i=0;i<containsSecondThread;i++)
{
sizeOfTask1 += threadArray[i]+" ";
}
int begOfTask3 = Task3.beg;
String checkingString = "";
for(int i=begOfTask3;i<threadArray.length;i++)
{
checkingString += i + " ";
}
String task3String = "";
for(int j = begOfTask3;j<threadArray.length;j++)
{
task3String += threadArray[j]+" ";
}
if((!oneAndTwo.contains(begOfTask3+"") && sizeOfTask1.contains(Task2.beg+"")) || task3String.equals(checkingString))
{
return true;
}
return false;
}
public static void main(String[] args) throws InterruptedException
{
Scanner sc= new Scanner(System.in);
Solution solution = new Solution();
int one = sc.nextInt();
Task1.a = one;
Task1.beg = 0;
int two = sc.nextInt();
Task2.a = two;
Task2.beg = one;
int three = sc.nextInt();
Task3.a = three;
Task3.beg = one+two;
System.out.print(solution.test());
}
}
First, some observations regarding your code: Instead of using static variables in the classes (i.e., Task1, Task2, and Task3) that extend the class Thread (to understand why have a look at Why are static variables considered evil?):
static int a = 0;
static int beg = 0;
use non-static final fields, and initialize them via the constructor:
class Task1 extends Thread
{
private final int begin;
private final int end;
Task1(int begin, int end){
this.begin = begin;
this.end = end;
}
public void run(){
for(int i=begin; i<= end; i++)
....
}
}
adapt the main method accordingly:
public static void main(String[] args){
...
Task1 task1 = new Task1(begin, end);
}
and then pass the tasks-related objects as parameters of to the test method:
public boolean test(Task1 task1, Task2 task2, Task3 task3){
...
}
For the concatenation of the strings use StringBuilder:
StringBuilder oneAndTwo = new StringBuilder();
for(int i=0;i<first;i++)
{
oneAndTwo.append(threadArray[i]).append(" ");
}
This looks wrong:
Task1.a = one;
Task1.beg = 0;
by looking at the loop of the run method from Task1, this means that, if Task1.a is not a negative number, then Task1 will not do any work.
To use the threads to generate the random values of the array:
int[] threadArray = new int[300];
you can start by extracting a method to generate those random values, based on formula:
r.nextInt(high-low) + low;
this formula generates a random value between low and high.
Adapt the tasks, accordingly:
class Task1 extends Thread
{
private final Random random_values = new Random();
private final int low;
private final int high;
...
public int generate_random(){
return r.nextInt(high-low) + low;
}
public void run()
{
for(....)
{
Solution.threadArray[i] = generate_random();
...
}
}
}
Make sure to pass to the threads the information about the range of the random values to be generated (i.e., the low and high parameters), and the reference to the array that will be filled up with those random values (i.e., array int[] threadArray) . Also make sure that you split the iterations int[] threadArray among the threads. Therefore, each thread should generate a chunk of the random values. An example of such distribution would be:
Thread 1 : 0 to 100;
Thread 2 : 100 to 200;
Thread 3 : 200 to 300;
You can make this more robust and divide the array length by the number to threads and assign the work among threads, accordingly.
I could have provided you with the entire solution, but I feel that is better instead if I give you the pointers so that you can do it in your own.
EDIT: Based on the new edit of your question:
You just need to adapt the Task classes as follows:
class Task1 extends Thread {
static int a = 0;
static int beg = 0;
public void run(){
for(int i=beg;i < a;i++)
Solution.threadArray[i] = i;
}
}
class Task2 extends Thread {
static int a = 0;
static int beg = 0;
public void run(){
for(int i=beg; i< beg + a;i++)
Solution.threadArray[i] = i;
}
}
class Task3 extends Thread{
static int a = 0;
static int beg = 0;
public void run(){
for(int i=beg;i< a + beg;i++)
Solution.threadArray[i] = i;
}
}
Thread1 and Thread2 are supposed to access Common Resource in threadArray[0... Task1.a+Task2+a]. So we have to make use of static volatile variable i declared in Solution Class.
class Task1 extends Thread
{
static int a=0,beg=0;
public void run()
{
int k=Task1.beg;
int i1=0;
while(i1<Task1.a)
{
Solution.threadArray[Integer.parseInt(Solution.i)]=k++;
int a1=Integer.parseInt(Solution.i);
a1++;i1++;
Solution.i=a1+"";
try{
Thread.sleep(1);
}
catch(InterruptedException e){}
}
}
}
class Task2 extends Thread
{
static int a=0,beg=0;
public void run()
{
int y=0;
int k=Task2.beg;
while(y<Task2.a)
{
Solution.threadArray[Integer.parseInt(Solution.i)]=k++;
int a1=Integer.parseInt(Solution.i);
a1++;y++;
Solution.i=a1+"";
try{
Thread.sleep(1);
}
catch(InterruptedException e){}
}
}
}
Thread3 work independently after First 2 threads complete.
class Task3 extends Thread
{
static int beg=0,a=0;
public void run()
{
for(int i=Task3.beg;i<Task3.beg+Task3.a;i++)
{
Solution.threadArray[i]=i;
}
}
}
having a problem with my java program. I am a newbie to Java and just can't figure out what is exactly the issue with it. In short I've declared an array and a variable in main, I've created my method call and would like my array be passed into my method with the variable. I would then like the method to take my array and count the number of times my variable "8" occurs, get rid of the 8 out of the array and return a new smaller array back to main. Here is my code below. I feel as if I am just missing one block code any suggestions?
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < arrayA.length; x++)
{
System.out.print(arrayA[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
}
}
return arrayX;
}
}
you do not actually need to return the array because when you pass an array to a method you also pass its memory address meaning its the same address that you change so, it will also change the arraysA of main method because you are just changing the values of the same memory adress
import java.util.*;
public class Help
{
public static void main(String[] args)
{
ArrayList<Integer> arraysA = new ArrayList<Integer>();
arraysA.add(Integer.valueOf(2));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(19));
arraysA.add(Integer.valueOf(32));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(18));
arraysA.add(Integer.valueOf(25));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(3));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
int varB=8;
newSmallerArray(arraysA,varB);
for(Integer i:arraysA)
{
System.out.println(i);
}
}
public static void newSmallerArray(ArrayList<Integer> arraysA,int varB)
{
for(int i=0;i<arraysA.size();++i)
{
if(Integer.valueOf(arraysA.get(i))==varB)
{
arraysA.remove(i);
}
}
}
}
Try this code it will not require for loop:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(arrayA));
list.removeAll(Arrays.asList(8));
arrayA = list.toArray(array);
The problem is in method "calculusRank". If I delete that method and related parts to it, aplication will work, if I create a different notepad with same code(method and main code related to that method) it's work.
Also I wanna say I'm a beginner and this is my first "relative" large application.
This is the code with problem that doesn't compile:
import java.util.Random;
import java.lang.Math;
public class MultilevelSystem1 {
static String[][] createMembers (int a) {
Random nr = new Random ();
String[][] membersName = new String [a][2];
for(int j=0; j<2;j++)
for(int i=0; i<a; i++) {
if(j==0||i==0) membersName[i][j]="Nume"+(i+1);
else membersName[i][j]="Nume"+(nr.nextInt(i)+1);
}
return membersName;
}
static String[][] createIncomes (String[][] a,int b){
Random nr = new Random ();
String[][] incomes = new String [b][2];
int j=0;
for(int i=0;i<a.length && j<b;i++)
if(nr.nextInt(2)==1){ incomes[j][0]= a[i][0];
incomes[j][1]=Integer.toString((nr.nextInt(10)+1)*50);
j++;}
return incomes;
}
static class Members extends MultilevelSystem1 {
double capital;
String name;
int rank;
String superior;
int ID;
int calculateRank (int r, Members[] membersArray) {
if(this.superior!=null)
for(int i=0;i<membersArray.length;i++)
if((this.superior).equals(membersArray[i].name)){r=membersArray[i].calculateRank(r,membersArray);
r++;
break;}
return r;
}
static int[] calculate (int[] a, int[] b) {
int[] c= new int [a.length];
for (int i=0; i<a.length; i++)
c[i]=a[i]+b[i];
return c;
}
}
public static void main(String[] args) {
final int n = 30;
final int m = 10;
int[] a={1,2,3,4,5};
int[] b={1,2,3,4,5};
int[] c= calculate(a,b);
for(int i=0;i<c.length;i++)
System.out.print(c[i]+" ");
String[][] entryDataMembers = createMembers(n);
String[][] entryDataIncomes = createIncomes(entryDataMembers,m);
Members[] membersArray = new Members[n];
for (int i=0; i<n; i++) {
membersArray[i]=new Members();
membersArray[i].name = entryDataMembers[i][0];
if(i!=0) membersArray[i].superior= entryDataMembers[i][1];
else membersArray[0].superior= null;
}
for (int i=0; i<n; i++)
membersArray[i].rank = membersArray[i].calculateRank(1,membersArray);
}
}
And this work:
public class test {
static int[] calculate(int[] a, int[] b) {
int[] c= new int [a.length];
for (int i=0; i<a.length; i++)
c[i]=a[i]+b[i];
return c;
}
public static void main (String[]args) {
int[] a={1,2,3,4,5};
int[] b={1,2,3,4,5};
int[] c= calculate(a,b);
for(int i=0;i<c.length;i++)
System.out.print(c[i]+" ");
}
}
int[] c = Members.calculate(a,b);
In you code there is compilation issue for calculate(a,b) method, this method present inside Members class. calculate(a,b) is static method so you can call this method using Members class.
The method which compiler couldn't find is "calculate".
Use
int[] c= Members.calculate(a,b);
to access static method of member class. (Around 62 line of code inside main method)
class max{
public int buy;
public int sell;
public max(int n){
buy=0;
sell=0;
}
}
public class MaxProfit{
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
int i=0,count=0;
while(i<n-1){
while((i<n-1)&&(a[i+1]<=a[i]))
i++;
if(i==n-1)
break;
//System.out.println(sol[count].buy=i++);
sol[count].buy=i++;
i++;
while((i<n)&&(a[i]>=a[i-1]))
i++;
sol[count].sell=i-1;
count++;
}
for(int k=0;k<count;k++)
System.out.println(sol[k].buy +sol[k].sell);
}
public static void main(String []args){
MaxProfit f=new MaxProfit();
int arr[]={20,100,260};
f.stock(arr,arr.length);
System.out.println("Hello World");
}
}
A Exception is coming which is exception in thread "main" java.lang.NullPointerException
at MaxProfit.stock(MaxProfit.java:15)
at MaxProfit.main(MaxProfit.java:32)
I am not able to solve this I have initialized array of max still I am getting null pointer exception Please help
You should initialize the elements of max[] sol maybe in a loop.
for(int i=0;i<sol.length;i++){
sol[i]=new max(aValue);
}
You are declaring an array (sol) but you are not filling your array with objects max. before using your array fill it first. Just add this to initialize your array:
max[] sol=new max[n/2+1];
for(int i = 0; i < sol.length; i++) {
sol[i] = new max(i /* or whatever the value that must be here */);
}
max[] sol=new max[n/2+1];
just defines and array with no (null) contents. You must put valid max objects in it. Like
max[i] = new max(/*param*/);
sol[count].buy=i++;
is throwing the NPE
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
for (int k = 0; k < sol.length; k++) {
sol[k]= new max(k);
}
int i=0,count=0;
while(i<n-1){
class Memory{
private int[] memoryArray;
private int size;
public Memory(int n)
{size = n;
memoryArray = new int[n];
for(int i=0;i<n;i++)
memoryArray[i] = -1;
}
public void write (int loc,int val)
{if (loc >=0 && loc < size)
memoryArray[loc] = val;
else
System.out.println("index out of range");
}
public int read (int loc)
{return memoryArray[loc];
}
}
Here is my program to test it...
class Test{
public static void main(String[] args)
{
Memory mymem = new Memory(100);
mymem.write(98 , 4);
int x;
x = mymem.read(98);
System.out.println(mymem);
mymem.dump();
for(int i=0;i<size;i++)
if(i%10==0)
System.out.println(memoryArray[i]);
else
System.out.println(memoryArray[i]);
}
}
So when I type in java Memory to run it I get an error saying "Exception in thread "main" java.lang.NoSuchMethodError:main and when I run java Test it outputs Memory#9931f5....How can I fix this?
Your Memory class does not have a main() method.
You probably want to type java Test.
Regarding your other problem, memoryArray isn't visible from your Test class. And Memory doesn't have a dump method.