I have a static variable and updating it's value in class. But when i access this variable from another class , it shows unupdated value.
CLASS A
public static int postID = 1;
public static String Creator()
{
String message = "POST id="+postID;
return message;
}
void updatePostID()
{
postID++; //this function is being called each 10 seconds
}
#Override
public void start() {
handler.post(show);
}
Handler handler = new Handler();
private final Runnable show = new Runnable(){
public void run(){
...
updatePostID();
handler.postDelayed(this, 10000);
}
};
CLASS B
String message = A.Creator(); //this always prints postID as 1 all time
I need a global variable that i can access from each class and update its value. Waiting for your help (I am using this with a Android Service)
this is a tested code .
public class A {
public static int id = 0;
public static int increment(){
return A.id++;
}
}
public class B {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(A.increment());
}
}
}
class A
{
static int id=0;
//I am updating id in my function ,
{
id++;
}
}
public class StartingPoint {
public static void main(String... args){
A a = new A();
A b = new A();
System.out.println(A.id);
System.out.println(a.id);
}
}
You need to call work to execute id++;
class B {
public static void main(String... args){
A a = new A();
a.work(); // You need to call it to apply add operation
System.out.println(A.id); // Prints 1
}
}
And this is a sample class A:
class A {
static int id = 0;
public void work(){
id++;
}
}
Save class A in a file named A.java and class B in a file named B.java.
Then compile B. Since B creates an instance of class A, A will be compiled and you don't need to compile A separately-
javac B.java
After compilation, to execute/run-
java B
Sajal Dutta's answer explains it perfectly, but if you want to keep it ALL static (i.e. not create any objects of class A, you could modify the code slightly to this:
class A {
static int id = 0;
public static void work(){
id++;
}
}
Then:
class B {
public static void main(String[] args){
System.out.println(A.id);
A.work();
System.out.println(A.id);
}
}
This would produce:
0
1
Edit (with regard to your updated question)
Where are you specifying the update of the static int? From the code you've provided all you will do is print out the same int over and over as the method containing the increment process is never called.
Edit 2:
Try this:
Change:
handler.post(show);
to:
handler.postDelayed(show, 10000);
Related
package staticassignment3;
public class Booking {
private String customerEmail;
private int seatsRequired;
private static int seatsAvailable;
private boolean isBooked;
static {
seatsAvailable = 400;
}
public Booking(String customerEmail, int seatsRequired) {
this.customerEmail = customerEmail;
this.seatsRequired = seatsRequired;
}
public String getCustomerEmail() {
return this.customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail= customerEmail;
}
public int getSeatsRequired() {
return this.seatsRequired;
}
public void setSeatsRequired(int seatsRequired) {
this.seatsRequired = seatsRequired;
}
public static int getSeatsAvailable() {
return Booking.seatsAvailable;
}
public static void setSeatsAvailable(int seatsAvailable) {
Booking.seatsAvailable = Booking.seatsAvailable - this.seatsRequired;
}
public boolean isBooked() {
if(Booking.seatsAvailable>= this.seatsRequired) {
Booking.setSeatsAvailable(seatsAvailable);
this.isBooked = true;
}
else {
this.isBooked = false;
}
return isBooked;
}
}
In the above Booking class, I want to update the static variable seatsAvailable by using the static method setSeatsAvailable but I am passing a nonstatic variable in it i.e this.seatsRequired which is not permitted. Is there any alternative to update the seatsAvailable without changing the code so much?
package staticassignment3;
public class Tester {
public static void main(String[] args) {
Booking booking1 = new Booking("jack#email.com", 100);
Booking booking2 = new Booking("jill#email.com", 350);
Booking[] bookings = { booking1, booking2 };
for (Booking booking : bookings) {
if (booking.isBooked()) {
System.out.println(booking.getSeatsRequired()+" seats successfully booked for "+booking.getCustomerEmail());
} else {
System.out.println("Sorry "+booking.getCustomerEmail()+", required number of seats are not available!");
System.out.println("Seats available: "+Booking.getSeatsAvailable());
}
}
}
}
in above Booking class i want to update seatsAvailable static variable by using setSeatsAvailable static method but i am passing nonstatic varible in it i.e this.seatsRequired which is not permitted.is there any alternate to achive the updated seatsAvailable static varibale without doing major changes in code
When calling a static method, there is no assocated object instance. So, it is not valid to use this inside a static method, since this refers to the current object (but you have none).
Specfically, this method isn't correct:
public static void setSeatsAvailable(int seatsAvailable) {
Booking.seatsAvailable = Booking.seatsAvailable - this.seatsRequired;
}
If you want to keep the method static, you could pass an additional parameter to the method – an instance of Booking – and then replace this.seatsRequired with booking.seatsRequired, like this:
public static void setSeatsAvailable(int seatsAvailable, Booking booking) {
Booking.seatsAvailable = Booking.seatsAvailable - booking.seatsRequired;
}
Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.
I'm searching for modifier in Java that has the same exact purpose as Static in C++ has. I mean, that variable is only initialized once in function, then every time we call that function again, values from the previous call are saved. That's how code looks in C++:
void counter()
{
static int count=0;
cout << count++;
}
int main()
{
for(int i=0;i<5;i++)
{
counter();
}
}
and the output should be 0 1 2 3 4, is there something that has the same purpose, but in Java?
looks like you are starting with java. To help you understand the concept i wrote the same code with comments for your understanding.
package yourXYZpackage;
public class yourABCclass{
//Declare in class body so your methods(functions) can access
//and the changes made will be global in C++ context.
static int count=0;
void counter()
{
count = count++;
System.out.println(count);
//thats how you can display on console
}
//this is the main method like C++
public static void main(String[] args){
for(int i=0;i<5;i++)
{
counter();
}
}
}
hope this will help..//
u need to create a constructor first.
public class answer2 {
static int count =0;
answer2() {
System.out.println(count);
count++;
}
public static void main(String[]args) {
for(int i=0;i<5;i++) {
new answer2();
}
}
}
just define static variables as a class member normally. java developers promote object oriented programming so even your main function is a method defined in another class whose name is same as your program name.
now for your question if you want to define a static variable:
public class abc
{
public static int count = 0;
}
public class xyz
{
public void increment()
{
abc.count++;
}
public static void main(String[] args)
{
System.out.println(abc.count);
increment();
System.out.println(abc.count);
}
}
Hope it helps.
public class Demo {
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
int size = 0;
inc(size);
System.out.println(size);
}
public int inc(int size){
size++;
return size;
}
}
When I call the code above, the number zero is returned.
Even declaring size as a class attribute instead of a local variable does not solve the problem. I understand that when a method is complete, the corresponding record (containing local variable and such) is popped off of the activation stack. But, if the size variable is declared in the init() method, and then incremented and returned in a separate method (inc()), shouldn't size be equal to 1?
When incrementing you do not assign the value to anything, it increments it, but it does not store it anywhere so the value remains 0, try doing like this.
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
size = inc(size);
System.out.println(size);
}
public int inc(int size)
{
size++;
return size;
}
}
or like this
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
System.out.println(inc(size));
}
public int inc(int size)
{
size++;
return size;
}
}
size = inc(size);
will solve your problem, since you are not using a public scoped variable.
If you want to make this a bit elegant (at least I think this will be a bit more handy), then you need to declare a variable as a class variable.
I will illustrate this to you:
public class Demo {
int size; //global range variable
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
this.size = 0;
inc();
System.out.println(this.size);
}
public void inc(){
this.size++; //will increment your variable evertime you call it
}
}
Hello So I have a entire class called tractor with different data's stored in it but now I'm suppose to create an object call tractor with a zero parameter constructor but This is the code I have so far and its giving em errors
First off this my Tractor Class which is in a different file:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
The error is :
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
You have compilation errors. You need to first declare the Tractor class then add the constructor inside it. One way to do is declare in a separate file. Also in Java unless you had defined d you couldnt have assigned it. Maybe you wanted to assign the day as a String look in the examples I provide below.
You need to to first create a file call Tractor.java and then define variables there. For example contents of Tractor.java:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
Then in your main method You can do Tractor trac = new Tractor(); or Tractor trac = new Tractor("tuesday"); also after that you can print the rentaldays of trac using System.out.println(trac.rentaldays);
From the looks of it you will probably be making a tractor rental system. In that case, rentalDays may be an array of Strings. And then you would have an array of Tractor objects to store in the rental system. You can look at these terms and keywords to point you in the right direction.
You are defining it wrong, define your methods inside class then call them in main() method.
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
you use an illegal of java syntax, if you already have class tractor in your project. for calling it to in other class, try below code
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
//This is just a sample
in your tractor class add below code
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
And keep your TestTractor class as
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}