wrapping around minutes into hours - java

I'm doing simple clock which wraps around when reaching 0 (e.g 00:59 -> 01:00, 23:59 -> 00:00). I got stuck at this moment and can't figure it out.
I have to do this in this way, using just methods given in 'BoundedCounter' class.
public class Test3 {
public static void main(String[] args) {
BoundedCounter minutes = new BoundedCounter(59, 0);
BoundedCounter hours = new BoundedCounter(23, 0);
int i = 0;
while (i < 70) { //repeats actual time 70 times - just to check if works fine
//put code here
i++;
}
}
}
.
import java.text.DecimalFormat;
public class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void next() {
value++;
if (value > upperLimit) {
value = 0;
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}

One variant is to use handlers:
import java.text.DecimalFormat;
public class Test3 {
public static void main(String[] args) {
final BoundedCounter minutes = new BoundedCounter(59, 0);
final BoundedCounter hours = new BoundedCounter(23, 0);
minutes.setOverflow(hours::next);
hours.setOverflow(minutes::reset);
for (int i = 0; i < 70; i++) { //repeats actual time 70 times - just to check if works fine
minutes.next();
System.out.println(hours.toString() + ":" + minutes.toString());
}
}
public static class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
private Runnable c;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void reset() {
this.value = startValue;
}
public void setOverflow(final Runnable c) {
this.c = c;
}
public void next() {
if (++value > upperLimit) {
value = 0;
c.run();
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}
}

Maybe this will help... To show current time use:
System.out.println(hours.toString() + ":" + minutes.toString());
To increment hours: hours.next()
To increment minutes: minutes.next()

Related

Creating a static average price method

Good afternoon, I can't write a static method to calculate the average price
Implement a static method to calculate the average price of goods in all baskets. It should calculate and return the ratio of the total cost of all baskets to the total number of all items.
Implement the static method for calculating the average cost of a basket (the ratio of the total cost of all baskets to the number of baskets).
I still have not been able to create static method data
public class Basket {
private static int count = 0;
private String items = "";
private int totalPrice = 0;
private double totalWeight = 0;
private int limit;
public static int allprice = 0;
public static int allcount = 0;
public static int averagebasket = 0;
public Basket() {
increaseCount(1);
items = "Список товаров:";
this.limit = 1000000;
}
public Basket(int limit) {
this();
this.limit = limit;
}
public Basket(String items, int totalPrice) {
this();
this.items = this.items + items;
this.totalPrice = totalPrice;
}
public static int getCount() {
return count;
}
public static int getAllTovar() {
return allcount;
}
public static int getAllPrice() {
return allprice;
}
public static int getAverageBasket() {
return averagebasket;
}
public double getTotalWeight(){
return totalWeight;
}
public static void increaseCount(int count) {
Basket.count = Basket.count + count;
}
public static void increaseTovar(int count) {
Basket.allcount = Basket.allcount + count;
}
public static void increasePrice(int totalPrice) {
Basket.allprice = Basket.allprice + totalPrice;
}
public static void average() {
Basket.averagebasket = allprice / allcount;
}
public void add(String name, int price, double weight) {
add(name, price, 1, weight);
}
public void add(String name, int price, int count, double weight) {
boolean error = false;
if (contains(name)) {
error = true;
}
if (totalPrice + count * price >= limit) {
error = true;
}
if (error) {
System.out.println("Error occured :(");
return;
}
increaseTovar(1);
items = items + "\n" + name + " - " +
count + " шт. - " + price + " Вес - " + totalWeight;
totalPrice = totalPrice + count * price;
totalWeight = totalWeight + weight;
Basket.allprice += price * count;
}
public void clear() {
items = "";
totalPrice = 0;
}
public int getTotalPrice() {
return totalPrice;
}
public boolean contains(String name) {
return items.contains(name);
}
public void print(String title) {
System.out.println(title);
if (items.isEmpty()) {
System.out.println("Корзина пуста");
} else {
System.out.println(items);
}
}
}
`
`public class Main {
public static void main(String[] args) {
Basket basket = new Basket();
basket.add("Milk", 40, 305.4);
basket.print("Milk");
//System.out.println(Basket.getCount());
Basket vasya = new Basket();
basket.add("bread", 60, 555);
System.out.println(Basket.getAllTovar());
System.out.println((Basket.getAllPrice()));
System.out.println(Basket.getAverageBasket());
}
}
Something like this?
public static double getAveragePrice() {
return (double) allPrice / allCount;
}
public static double getAverageBasket() {
return (double) allPrice / basketCount;
}

How can I implement a thread that gets user input?

I've implemented a thread that get user input by keyboard. However, when user sets input my program returns an IllegalThreadStateException error, at line 23.
import java.util.Scanner;
public class Main {
static MyThread myThread = new MyThread();
static public boolean answered = false;
public static void main(String[] args) {
String s = "";
while (!s.equalsIgnoreCase("q")) {
int seconds = 0, average = 5;
if (seconds > average) {
myThread.stop();
String phrase = choosePhrase(seconds, average);
System.out.println(phrase);
Scanner keyboard = new Scanner(System.in);
s = keyboard.nextLine();
} else {
long createdMillis = System.currentTimeMillis();
myThread.start();
while (!answered && seconds < average) {
long nowMillis = System.currentTimeMillis();
seconds = (int) ((nowMillis - createdMillis) / 1000);
}
}
}
}
private static String choosePhrase(int seconds, int average) {
if (seconds > average + 10) {
return "¿D?";
} else if (seconds > average + 5) {
return "¿E?";
} else {
return "¿F?";
}
}
}
class MyThread extends Thread {
static String[] questions = {"¿A?", "¿B?", "¿C?"};
public void run() {
System.out.println("MyThread running");
Double d = Math.random() * 100;
int n = (int) (Math.ceil(d) % 3);
String question = questions[n];
System.out.println(question);
Scanner keyboard = new Scanner(System.in);
String s = keyboard.nextLine();
stop();
}
}
Why am I getting this exception? How do I make the thread gets and exits correctly to main function?
To make a thread exits proprely you have to use myThread.interrupt();
I've solved the issue with your suggestions:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
Latency latency = new Latency();
latency.start();
}
}
class Latency {
int seconds = 0, average = 5;
MyThread myThread;
ObjectToPass o = new ObjectToPass();
public void start() {
String s = "";
Thread t = null;
while (!s.equalsIgnoreCase("q")) {
// The program has just begun, or user has answered a question,
// or term has expired.
seconds = 0;
if (myThread != null) {
myThread.shutdown();
myThread = null;
}
if (o.answered) {
o.answered = false;
myThread = new MyThread(o, new String[]{"¿A?", "¿B?", "¿C?"});
} else {
myThread = new MyThread(o, new String[]{"¿D?", "¿E?", "¿F?"});
}
t = new Thread(myThread);
t.start();
long createdMillis = System.currentTimeMillis();
while (!this.o.getPlay() && seconds < average) {
long nowMillis = System.currentTimeMillis();
seconds = (int) ((nowMillis - createdMillis) / 1000);
}
}
}
}
class ObjectToPass {
boolean answered = true;
public synchronized boolean getPlay() {
return answered;
}
public synchronized void setPlay(boolean answered) {
this.answered = answered;
}
}
class MyThread implements Runnable {
ObjectToPass o;
static String[] questions;
public MyThread(ObjectToPass o, String[] questions) {
this.o = o;
this.questions = questions;
}
public void run() {
// System.out.println("MyThread running");
Double d = Math.random() * 100;
int n = (int) (Math.ceil(d) % 3);
String question = questions[n];
System.out.println(question);
// Scanner keyboard = new Scanner(System.in);
// String s = keyboard.nextLine();
Object[] options = {"Yes", "No"};
int oo = JOptionPane.showOptionDialog(null,
question, "Question", JOptionPane.YES_OPTION,
JOptionPane.NO_OPTION, null, options, options[0]);
this.o.setPlay(true);
}
public void shutdown() {
Thread.currentThread().interrupt();
return;
}
}

Can I use a void method with a label.setText?

My question is if it possible to use a void method in a setText for a Label? I'm working at the moment on school homework on Netbeans and I want to use the 'public void printTable()' in a Label but the programm always say that it is impossible to use a void here and I know that normally I should use a return statement but in the instruction is written that I should use a 'void'.
Here you can see my Java Class
public class AffineFunction
{
private int a;
private int b;
public int getA()
{
return a;
}
public int getB()
{
return b;
}
public void setA(int newA)
{
a = newA;
}
public void setB(int newB)
{
b = newB;
}
public AffineFunction(int pA, int pB)
{
a = pA;
b = pB;
}
public int solve(int x)
{
return (a*x)+b;
}
public void printTable()
{
for(int i =-10; i<=10; i++)
{
System.out.println("F(" + i + ") = " + solve(i));
}
}
public void printTable(double step)
{
for(double i = - 10 ; i<= 10; i = i + step)
{
System.out.println( "F(" + i + ") = " + solve((int)i));
}
}
}
Here is a part of my JFrame :
//E
int a = Integer.valueOf(aTextField.getText());
int b = Integer.valueOf(bTextField.getText());
int x = Integer.valueOf(xTextField.getText());
//T
AffineFunction affineFunction = new AffineFunction(a, b);
//S
FLabel.setText(String.valueOf(affineFunction.solve(x)));
printTableLabel.setText(String.valueOf(affineFunction.printTable()));

RPG game code error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);

transfer form one state to another

I use centralized patter to coding vending machine. The problem is I found out that I cannot change states. In the constructor, I initialized state to Ls[0], but when I go to the method public void coin() to change the state, I found that the state doesn't changed. The part of my code is:
class Vending_machine {
State st;
private int price;
private int k;
private int k1;
private int t;
private int s;
private State[] Ls;
public Vending_machine() {
Ls = new State[7];
Ls[0] = new Idle();
Ls[1] = new Coins_inserted();
Ls[2] = new Sugar();
Ls[3] = new No_small_cups();
Ls[4] = new No_large_cups();
Ls[5] = new Exit();
Ls[6] = new Start();
st = Ls[0];
st.vm = this;
k = 0;
k1 = 0;
t = 0;
price = 0;
s = 0;
}
public void setK(int k) {
this.k = k;
}
public int getK() {
return k;
}
public void setS(int s) {
this.s = s;
}
public int getS() {
return s;
}......
public void coin() {
st.coin();
if (st.getId() == 0) {
if (t + 25 < price) {
// t=t+25;
st = Ls[0];
}
if (t + 25 >= price && price > 0) {
// s=0;
// t=0;
st = Ls[1];
}
}......
class State {
public Vending_machine vm;
int id = 0;
public void coin() {}
public void small_cup() {}
public void large_cup() {}
public void sugar() {}
public void tea() {}
public void insert_large_cups(int n) {}
public void insert_small_cups(int n) {}
public void set_price(int p) {}
.......
}
class Idle extends State {
public void coin() {
if (vm.getT() + 25 < vm.getPrice()) {
vm.setT((vm.getT()) + 25);
System.out.println(vm.getT());
}
else if ((vm.getT() + 25 >= vm.getPrice()) && (vm.getPrice() > 0)) {
vm.setS(0);
vm.setT(0);
}
}......

Categories