Idee für Methodenrumpf

Ru$h

Aktives Mitglied
Hallo,
ich möchte gerne eine Methode schreiben, die mir einen Int-Wert zurückgibt, dieser Wert bei 3 anfängt und fortlaufend um 2 erhöht wird, wenn ich die Methode erneut aufrufe.
Wie kann ich das machen?
 
Ganz einfach:
Java:
class Test {
  private int value = 3;

  public int getAndIncrementByTwo() {
    int v = value;
    value += 2;
    return v;
  }
}
oder spannender:
Java:
class Test {
  private int value = 3;
 
  public int getAndIncrementByTwo() {
    try {
      return value;
    } finally {
      value += 2;
    }
  }
}
oder built-in:
Java:
class Test {
  private AtomicInteger val = new AtomicInteger(3);
  
  public int getAndIncrementByTwo() {
    return val.getAndAdd(2);
  }
}
 
Schlüsselwort: statische Variablen
Java:
public class Things {
 
    final static int GAIN = 2;
    final static int GAIN_ON_START = 3;
    static int counter = 3;

    public Things() {
    }
 
 
    public void gainCounter()
    {
        counter += Things.GAIN;
    }
 
    public void resetCounter()
    {
        counter = Things.GAIN_ON_START;
    }
 
    public int getCounterInfo()
    {
        return counter;
    }
 
}
Java:
package beispiel;

public class Beispiel {

    public static void main(String[] args) {

   
      Things things = new Things();
      things.gainCounter();
      System.out.println(things.getCounterInfo());
      things.resetCounter();
      System.out.println(things.getCounterInfo());
      things.gainCounter();
      things.gainCounter();
      System.out.println(things.getCounterInfo());

    }
}
/** Konsolenausgabe */
5
3
7
 

Neue Themen


Zurück
Oben