My program is not returning the expected output, I tried very hard but I don't know how to do for this code. What can I do ?
Expected output
1 2 3 4 5 6 7 8 ......2000
Actual output
1 2 3 4 5 6 1 2 3 4 5 6 ..1000
Main
public class Race_ConditonTest {
public static void main(String[] args) {
Race_Condition2 R1 = new Race_Condition2();
Race_Condition2 R2 = new Race_Condition2();
R1.start();
R2.start();
}
}
RaceCondition2 (sub class)
public class Race_Condition2 extends Thread{
Race_Condition R= new Race_Condition();
public void run() {
R.sum();
}
}
RaceCondition class (super class)
public class Race_Condition {
int x=0;
public int Load(int x){
return x;
}
public void Store(int data) {
int x= data;
System.out.println(x);
}
public int Add(int i,int j) {
return i+j ;
}
public void sum() {
for (int i=0 ; i<1000 ; i++) {
this.x=Load(x);
this.x=Add(x,1);
Store(x);
}
}
}
how can i share x ?
simple way> make x static.
...
static int x=0;
...
Edit
After some tests, if you find something weird happening then make the Store function synchronized.
public synchronized void Store(int data) {
int x= data;
System.out.println(x);
}
check out how synchronized work synchronized
If your goal is to make the attribute x shared between R1 and R2 you could make it static in the RaceCondition class.
static int x=0;
Take care that if x is shared, they will be concurrent access to it, so some weird output could produce. Make the function that access x synchronized (as described here) :
// static cause it only access a static field
// synchronized so the access the the shared resource is managed
public static synchronized void sum() {
for (int i=0 ; i<1000 ; i++) {
this.x=Load(x);
this.x=Add(x,1);
Store(x);
}
}
You should probably make the same changes on the other functions.
Related
Given:
public class Counter {
private int count;
public Counter() {
count = 5;
}
public void increment() {
count++;
}
public void reset() {
count = 0;
}
public int value() {
return count;
}
}
If I have a subclass with a defined function (not implicitly created), does the subclass constructor inherit the instance variable count from the superclass constructor? I ask this because I'm running into a bit of a confusion with regards to private count.
public class ModNCounter extends Counter {
int modCount;
public ModNCounter(int n) {
modCount = n;
}
#Override
public int value() {
return super.value() % modCount;
}
public static void main(String[] args) {
ModNCounter modCounter = new ModNCounter(3);
System.out.println(modCounter.value()); //prints out 5 % 3 = 2
modCounter.increment(); // count = 6
System.out.println(modCounter.value()); //prints out 6 % 3 = 0
modCounter.reset(); // count = 0
modCounter.increment(); // count = 1
System.out.println(modCounter.value()); //print 1 % 3 = 1
}
}
Does the object modCounter have a count variable? If not, why is modCounter.increment() not giving me an error?
An inherited class has all the members of its superclass, although they may not be directly accessible to it (if they are private). In this case - yes, an instance of ModNCount has a count member. It cannot access it since it's private, but, as you've seen, it can affect its value using the increment and reset methods.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to call the toh method from my main class(Driver). When I make the call it gives me a null pointer exception. How can I call the toh method in Hanoi from the driver class? When I combine the classes into one it works fine but I need them to be two separate classes. Also, I included the global variables I am using in both classes is that necessary? Any help is welcome. Thanks!
public class Hanoi {
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println("T"+cycle + " Pillar 1 | Pillar 2 | Pillar 3");
System.out.println("-------------------------------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println("\n");
cycle++;
}
}
Main class(driver):
public class Driver{
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
int num = 0;
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<>();
tower[2] = new Stack<>();
tower[3] = new Stack<>();
/* Accepting number of disks */
while(num <=0){
System.out.println("Enter number of disks(greater than 0):");
num = scan.nextInt();
}
N = num;
Hanoi.toh(num);
}
}
You are initializing your tower array inside your Driver class, however, you have not initialized it in your Hanoi class.
As I said in my comment, please do not write global variables twice, in different classes. This is because the different classes DO NOT share the same global variables. (when we say global variable, we mean that they are global to the Driver class only. To access those variables, use the dot operator)
For example, get rid of the N cycle and tower declarations from your Hanoi class
Then access those variables using the dot operator.
tower would become Driver.tower and N would become Driver.N and so forth.
Note: this only works if your Driver class is static, otherwise you would need to access it as an object attribute.
Try to initialize the tower array, something like this:
public static Stack<Integer>[] tower;
public static void toh( int n )
{
tower = new Stack[n];
for ( int d = 0 ; d < n ; d++ )
{
tower[d]=new Stack<>();
}
delete duplicated static values in a class (either Driver or Hanoi)
then in the class that no longer has the static values and add that class to the beginning of all the missing classes.
Ex:
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public static int MyVar;
public void bMethod(){
++MyVar;
}
}
↓ to ↓
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public void bMethod(){
++A.MyVar;
}
}
This question already has answers here:
Why do arrays change in method calls? [duplicate]
(6 answers)
Closed 7 years ago.
I'm confused about the method. I thought typically you need to return something. Or in my mind I would have thought the need for a for loop that passes the elements back from the method that adds 5 to each element.
However When the array is passed to the method, the array itself changes, but why?
public static void main(String[] args) {
int ray[]={3,4,5,6,7};
change(ray);
for(int y: ray){
System.out.println(y);
}
}
public static void change(int x[]){
for(int counter = 0; counter < x.length;counter++){
x[counter]+=5;
}
}
In Java, all objects are passed by reference, and arrays are objects. That means that your change method receives the same array that was created in main--not a copy of it, the same object. So when you modify it, the main method sees that change too.
Java is pass-by-value for primitives, and pass-by-reference(value) for everything else (including arrays).
http://javadude.com/articles/passbyvalue.htm
What that basically means is that your function does not get a copy of the array, it gets the array itself.
Try it with an int (the original value will not change, because it's a primitive).
public static void main(String[] args) {
int ray[]={3,4,5,6,7};
change(ray);
for(int y: ray){
System.out.println(y);
}
}
public static void change(int i){
i = i + 10;
}
public static void change(int x[]){
for(int counter = 0; counter < x.length;counter++){
x[counter]+=5;
}
}
Some will say that Java always passes by value, but that's because of a poor choice of definitions when it comes to references.
Objects are conceptually passed by reference, and primitives by value. You can call it what you like but it looks like a duck, walks like a duck and quacks like a duck.
Try this, you'll get a better idea:
/**
* Main
*
*/
public class Main {
static class IntegerClass {
int internal;
public IntegerClass(int i) {
internal = i;
}
public void setInternal(int i) {
internal = i;
}
public int getInternal() {
return internal;
}
}
public static void main(String[] a) {
int x = 10;
changeInteger(x);
System.err.println(x);
IntegerClass ic = new IntegerClass(10);
changeIntegerClass(ic);
System.err.println(ic.getInternal());
}
public static void changeIntegerClass(IntegerClass ic) {
ic.setInternal(500);
}
public static void changeInteger(Integer i) {
i = 500;
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I know Java foreach loops are only meant to read values and not assign them, but I was wondering if they can call mutator methods on object. To find out I designed an experiment. Unfortunately the experiment crashes and I'm curious as to why.
public class test {
public static void main(String[] args)
{
foo[] f = new foo[4];
/*this would be a foreach loop, once I got the program working normally*/
for(int i = 0; i < f.length; i++) {
System.out.println(f[i].get());
f[i].add();
System.out.println(f[i].get());
}
}
private class foo {
foo() {
int x = 5;
}
void add() {
x++;
}
int get() {
return x;
}
private int x;
}
}
Gives Exception in thread "main" java.lang.NullPointerException when I expected the output to be 5 6. Is it because the constructor to foo isn't being called? If so, how can it be called? Must foo be made a static class?
You have an array of null and have not initialized any of the Foo items in the array, meaning it holds nothing but nulls.
Foo[] foos = new Foo[4];
// you need to first do this! You need to fill your array with **objects**!
for (int i = 0; i < foos.length; i++) {
foos[i] = new Foo(); // ******* add this!!*******
System.out.println(foos[i].get()); // this will now work
foos[i].add();
System.out.println(foos[i].get());
}
// now you can use the array
As an aside, your x will be 0 initially because you shadow the variable in the Foo constructor.
public class Foo {
private int x;
Foo() {
// this **re-declares the x variable**
int x = 5;
}
//....
Instead you want to do:
public class Foo {
private int x;
Foo() {
x = 5;
}
//....
Aside #2: you will want to learn and use Java naming conventions. Class names should all begin with an upper-case letter and variable names with a lower-case letter. This is important if you need others (us!!) to understand your code quickly and easily.
An example of a single class. Call it Foo.java and have it hold only one class:
public class Foo {
private int x;
public Foo() {
x = 5;
// not!
// int x = 5;
}
public void increment() {
x++;
}
public void decrement() {
x--;
}
public int getX() {
return x;
}
public static void main(String[] args) {
int fooCount = 10;
Foo[] foos = new Foo[fooCount];
for (int i = 0; i < foos.length; i++) {
foos[i] = new Foo();
System.out.println(foos[i].getX());
foos[i].increment();
foos[i].increment();
System.out.println(foos[i].getX());
}
for (Foo foo : foos) {
foo.decrement();
foo.decrement();
foo.decrement();
System.out.println(foo.getX());
}
}
}
I have a quick question out of curiosity...if I declare an integer in one method, for example: i = 1, is it possible for me to take that i and use its value in my main class (or another method)? The following code may be helpful in understanding what I'm asking...of course, the code might not be correct depending on what the answer is.
public class main {
public main() {
int n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
No you cannot! Not unless you make it an instance variable!
Or actually send it to the function as an argument!
First, let's start simple. All methods that are not constructors require a return type. In other words,
public void number(){
i = 1;
}
would be more proper.
Second: the main method traditionally has a signature of public static void main(String[] args).
Now, on to your question at hand. Let's consider a few cases. I will be breaking a few common coding conventions to get my point across.
Case 1
public void number(){
i = 1;
}
As your code stands now, you will have a compile-time error because i is not ever declared. You could solve this by declaring this somewhere in the class. To access this variable, you will need an object of type Main, which would make your class look like this:
public class Main {
int i;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
i = 1;
}
}
Case 2
Let's say you don't want to make i a class variable. You just want it to be a value returned by the function. Your code would then look like this:
public class Main {
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
}
public int number(){ //the int here means we are returning an int
i = 1;
return i;
}
}
Case 3
Both of the previous cases will print out 1 as their output. But let's try something different.
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
int i = 1;
}
}
What do you think the output would be in this case? It's not 1! In this case, our output is 0. Why?
The statement int i = 1; in number(), it creates a new variable, also referred to as i, in the scope of number(). As soon as number() finishes, that variable is wiped out. The original i, declared right under public class Main has not changed. Thus, when we print out myMain.i, its value is 0.
Case 4
One more case, just for fun:
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
System.out.print(myMain.i);
}
public int number(){
int i = 1;
return i;
}
}
What will the output of this be? It's 10. Why you ask? Because the i returned by number() is the i in the scope of number() and has a value of 1. myMain's i, however, remains unchanged as in Case 3.
You may use a class-scope field to store you variable in a class object or you can return it from one method or pass it as a parameter to the other. Mind that you will need to call your methods in the right order, which is not the best design possible.
public class main {
int n;
int i;
public main() {
n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
Yes, create a classmember:
public class Main
{
private int i;
public main() {
int n = 1;
System.out.print(n + i);
number();
System.out.print(n + i);
}
public number(){
i = 1;
}
}
void method(){
int i = 0; //has only method scope and cannot be used outside it
}
void method1(){
i = 1; //cannot do this
}
This is because the scope of i is limited to the method it is declared in.