I want to get increasing value starting with 1 so that I get TK-1 all the way to TK-n.
What I've tried is:
public class Main {
addTicket();
public void addTicket() {
int a;
String ticket;
a = getA();
ticket = "TK-"+ a
System.out.println(ticket)
}
public int getA() {
int a, b;
a = 0;
b = a++;
return a;
public static void main(String[] args) {
new Main();
}
}
Sorry it's my first time learning to code, can someone explain to me why it isn't working and what should I do to make it work ?
Thanks in advance.
If you need an autoincrease ID, you need a static int:
public class Ticket {
static int ticketID = 1;
public void addTicket() {
int a;
String ticket;
a = getticketID();
ticket = "TK-" + a;
System.out.println(ticket);
}
public int getticketID () {
return ticketID++;
}
public static void main(String[] args) {
Ticket test = new Ticket();
test.addTicket();
test.addTicket();
test.addTicket();
}
}
output:
enter image description here
Related
I am developing a client-server in java and I encountered problem passing a custom Runnable implementation as argument from an object to another.
The problem is that the Runnable code is evaluated (not executed) at definition but I want it to be evaluated at invocation.
Is there any way to achieve this behavior?
Here the code affected by this problem:
Custom Runnable implementation
public abstract class ChallengeReportDelegation implements Runnable
{
private ChallengeReport fromChallengeReport = null;
private ChallengeReport toChallengeReport = null;
#Override
public abstract void run();
public ChallengeReport getFromChallengeReport()
{
return fromChallengeReport;
}
public ChallengeReport getToChallengeReport()
{
return toChallengeReport;
}
public void setFromChallengeReport(ChallengeReport fromChallengeReport)
{
this.fromChallengeReport = fromChallengeReport;
}
public void setToChallengeReport(ChallengeReport toChallengeReport)
{
this.toChallengeReport = toChallengeReport;
}
}
Here where the Runnable is passed as argument:
// Record challenge
this.challengesManager.recordChallenge(whoSentRequest, whoConfirmedRequest,
new ChallengeReportDelegation()
{
#Override
public void run()
{
ChallengeReport fromReport = getFromChallengeReport();
ChallengeReport toReport = getToChallengeReport();
sendMessage(whoSentRequest, new Message(MessageType.CHALLENGE_REPORT, String.valueOf(fromReport.winStatus), String.valueOf(fromReport.challengeProgress), String.valueOf(fromReport.scoreGain)));
sendMessage(whoConfirmedRequest, new Message(MessageType.CHALLENGE_REPORT, String.valueOf(toReport.winStatus), String.valueOf(toReport.challengeProgress), String.valueOf(toReport.scoreGain)));
}
});
The receiving object store the ChallengeReportDelegation instance as completionOperation, wait for a timeout then execute this code.
private void complete()
{
stopTranslations();
int fromStatus;
int toStatus;
if (this.fromScore > this.toScore)
{
fromStatus = 1;
toStatus = -1;
}
else if (this.fromScore < this.toScore)
{
fromStatus = -1;
toStatus = 1;
}
else
{
fromStatus = 0;
toStatus = 0;
}
this.completionOperation.setFromChallengeReport(new ChallengeReport(this.from, fromStatus,this.fromTranslationsProgress, this.fromScore));
this.completionOperation.setToChallengeReport(new ChallengeReport(this.to, toStatus, this.toTranslationsProgress, this.toScore));
this.completionOperation.run();
}
The code above raises a NullPointerException at the execution of the last portion of code, in the run method.
[EDIT]
The NullPointerException exception is thrown because both getFromChallengeReport() and getToChallengeReport() (second portion of code) initially return null (when the Runnable is defined and passed as argument),
but they would return consistent values at invocation time run() (third portion of code)
[EDIT2]
I reproduced the situation in this simple code:
public class TestEvaluation
{
public static void main(String[] args) throws InterruptedException
{
Middle middle = new Middle();
middle.register(new Task() {
#Override
public void run() {
System.out.println("a is: " + getA());
System.out.println("b is: " + getB());
}
});
Thread.sleep(2000);
}
abstract static class Task implements Runnable
{
private int a = 0;
private int b = 0;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
#Override
abstract public void run();
}
static class Middle
{
private ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);
public void register(Task task)
{
Leaf leaf = new Leaf(new Task() {
#Override
public void run() {
System.out.println("Middle");
task.run();
}
});
pool.schedule(leaf, 1, TimeUnit.SECONDS);
}
}
static class Leaf implements Runnable
{
public Task task;
public Leaf(Task task)
{
this.task = task;
}
#Override
public void run()
{
task.setA(5);
task.setB(5);
System.out.println("Leaf");
task.run();
}
}
}
The behavior that i want to achieve is the printing of
Leaf
Middle
a is: 5
b is: 5
But this is what i get
Leaf
Middle
a is: 0
b is: 0
A very simple example. Lets create a runnable with a field.
public static void main (String[] args) {
var x = new Runnable(){
int a = 0;
int getA(){
return a;
}
void setA(int v){
a = v;
}
public void run(){
System.out.println("A : " + getA());
}
};
x.run();
x.setA(5);
x.run();
}
The first time it is 0, the second time 5, because getA is evaluated when run is called.
I found a working solution for this problem, perhaps trivial for those coming from functional programming.
Accordingly to the example in last edit ([EDIT2])
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class TestEvaluation
{
public static void main(String[] args) throws InterruptedException
{
Middle middle = new Middle();
middle.register(new Consumer<Values>() {
#Override
public void accept(Values values) {
System.out.println("a is: " + values.getA());
System.out.println("b is: " + values.getB());
}
});
Thread.sleep(2000);
}
static class Values
{
private int a = 0;
private int b = 0;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
static class Middle
{
private ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);
public void register(Consumer<Values> passed)
{
Consumer<Values> middleConsumer = new Consumer<Values>() {
#Override
public void accept(Values values) {
System.out.println("Middle");
passed.accept(values);
}
};
Leaf leaf = new Leaf(middleConsumer);
pool.schedule(leaf, 1, TimeUnit.SECONDS);
}
}
static class Leaf implements Runnable
{
public Consumer<Values> task;
public Leaf(Consumer<Values> task)
{
this.task = task;
}
#Override
public void run()
{
Values values = new Values();
values.setA(5);
values.setB(5);
System.out.println("Leaf");
task.accept(values);
}
}
}
This code produces the behavior i want.
Hope this will help someone.
Cheers!
If you want to immediately evaluate something. I'd suggest not using a Runnable at all. It sound like an anti-pattern, trying to pass code around when all you want is the value/invocation.
Furthermore, try to use a Callable or Supplier instead since you are clearly interested in returning some values from the sub-routines.
Hey i want to write out table in second method.
In first i changed int x into table(each digit in other array index) and in second method i want to write out the table. How to do it ?
int tab [] =new int [4];
public int[] change(int x) {
System.out.print(tab[0]=x/1000);
System.out.print(tab[1]=(x/100)%10);
System.out.print(tab[2]=(x/10)%10);
System.out.println(tab[3]=x%10);
System.out.println(tab.toString());
return tab;
}
public void writeout(int a[]) {
this.tab=a;//how to connect tab from change() with int a[]
for( int i=0;i<=3;i++) {
System.out.println(a[i]);
}
You can use newest Java 8 API to print your array. Your code may look like this:
import java.util.Arrays;
public class App {
int tab[] = new int[4];
public int[] change(int x) {
tab[0] = x/1000;
tab[1] = (x/100)%10;
tab[2] = (x/10)%10;
tab[3] = x%10;
return tab;
}
public void writeout(int array[]) {
Arrays.stream(array).forEach(System.out::println);
}
public static void main(String[] args) {
App app = new App();
app.writeout(app.change(2));
}
}
I fiddled with it. It appears to work after adding a closing brace at the end. tab.toString() doesn't result in sensible results though.
public class MyClass {
public static void main(String args[]) {
MyClass c = new MyClass();
c.writeout(c.change(3));
}
public int[] change(int x) {
int tab [] =new int [4];
System.out.print(tab[0]=x/1000);
System.out.print(tab[1]=(x/100)%10);
System.out.print(tab[2]=(x/10)%10);
System.out.println(tab[3]=x%10);
System.out.println(tab.toString());
return tab;
}
public void writeout(int a[]) {
for( int i=0;i<=3;++i) {
System.out.println(a[i]);
}
}
}
If you want to use class fields, then you could do it like this:
public class MyClass {
public static void main(String args[]) {
MyClass c = new MyClass();
c.change(3);
c.writeout();
}
private int tab [] = new int [4];
public void change(int x) {
System.out.print(tab[0]=x/1000);
System.out.print(tab[1]=(x/100)%10);
System.out.print(tab[2]=(x/10)%10);
System.out.println(tab[3]=x%10);
}
public void writeout() {
for( int i=0;i<=3;i++) {
System.out.println(tab[i]);
}
}
}
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
}
}
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);
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
Now if I have to increment the variable... which one is the way of doing ?
variables.setA(variables.getA()+1);
in this way a always is 1.
can i solve the problem?
That code is correct (if verbose). The following:
public class Main {
private int a = 0;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public static void main(String[] args)
{
Main variables = new Main();
System.out.println(variables.getA());
variables.setA(variables.getA()+1);
System.out.println(variables.getA());
variables.setA(variables.getA()+1);
System.out.println(variables.getA());
variables.setA(variables.getA()+1);
System.out.println(variables.getA());
}
}
prints
0
1
2
3
Given the verbosity of variables.setA(variables.getA()+1), you might want to wrap it into a method (e.g. incrementA() or addToA(int) etc)
Your way of incrementing a variable should work, but you could also define a new method:
public void incrementA(){
a++;
}