Java Swing Timer getting faster and faster - java

I'm working on a small turn based RPG. For every turn, one of the two characters tries to hit the other character then 2000ms later, the timer restarts the attack method (to give time to the player to read the outcome of each turn). After the battle, the player goes back to the level map where he can choose to move away or initiate another battle. Here's my problem: Every time the player initiates a new battle, the Timer delay is shorter and shorter so the battle happens too fast at some point. First fight, each turn will be 2 seconds, then 1 second, then 500ms, and so on. Here's my code, what am I missing?
public void attack(Character a, Character d) {
//Calculations//////////////////////////////////////////////
///////////////////unit a (attacker)////////////////////////
Weapon aWep = (Weapon) a.inventory[0];
double aCritRate = (double) (a.skl / 2 + aWep.crit - d.lck) / 100;
double aHitRate = (double) (aWep.acc + (a.skl * 2) + (a.lck / 2)) / 100;
double aAvoidRate = (double) (a.spd * 2 + a.lck) / 100;
int aAttackPower = (a.pow + aWep.dmg);
boolean aTwice = a.spd >= d.spd + 4 ? true : false;
///////////////////unit d (defender)////////////////////////
Weapon dWep = (Weapon) d.inventory[0];
double dCritRate = (double) (d.skl / 2 + dWep.crit - a.lck) / 100;
double dHitRate = (double) (dWep.acc + (d.skl * 2) + (d.lck / 2)) / 100;
double dAvoidRate = (double) (d.spd * 2 + d.lck) / 100;
int dAttackPower = (d.pow + dWep.dmg);
boolean dTwice = d.spd >= a.spd + 4 ? true : false;
int delay = 2000;
Timer timer;
ActionListener repeat = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
switch(bturn){
case(1):attack(d,a); break;
default:break;
}
}
};
timer = new Timer(delay,repeat);
//Battle/////////////////////////
int aDmg = aAttackPower - d.def;
double aHitChance = aHitRate - dAvoidRate;
String sound;
//Turn 1
if (aHitChance >= rngs[rngsIndex]) {
if (aCritRate >= rngs[rngsIndex]) {
aDmg *= 3;
sound="crit.wav";
t.print("Critical Hit! " + a.name + " attacks " + d.name + " for " + aDmg + " damage!");
rngsIndex++;
} else {
sound="hit.wav";
t.print(a.name + " attacks " + d.name + " for " + aDmg + " damage!");
rngsIndex++;
}
d.damageHp(aDmg);
rngsIndex++;
} else {
sound = "miss.wav";
t.print(a.name + " has missed.");
rngsIndex++;
}
playSound(sound);
if (d.isDead) {
String add = t.text.getText();
add+=" " + d.name + " has been killed.";
t.print(add);
a.xp+=35;
charPane.set(a);
grid[d.x][d.y].removeMouseListener(grid[d.x][d.y].hover);
killUnit(d, grid[d.x][d.y]);
}
if (d.faction.equals("e")) {
enemPane.set(d);
} else {
charPane.set(d);
}
//Turn 2
bturn++;
if(!d.isDead && bturn==1){
System.out.println("REACHED");
timer.start();
}
else{
timer.stop();
bturn = 0;
grid[d.x][d.y].removeActionListener(grid[d.x][d.y].targetable);
clearGrid();
loop();
}
}

Try to log which instance of ActionListener repeat caused the attack. I think you will see, that the speedup is caused by having more instances of Timer and ActionListener then you want.
After each run, number of those instances doubles, hence the exponencial growth of number of turns per second.
In absence of logger:
public void actionPerformed(ActionEvent e)
{
System.out.println("" + LocalDateTime.now() + " " + this);
switch(bturn){

Related

Problem Calculating Experience Points For The Next Level in a Text Based Game

for class I've been tasked with making a text based adventure game. Recently, I've been trying to program in battling and exp in the game. Here is what I am using to calculate it in the Player class:
int level = 1;
int exp = 0;
int close;
public void levelup() {
level += 1;
}
public int nextlevel() {
int x = level;
close = (4 * (x ^ 3) / 5);
return close;
}
public boolean levelready() {
return exp >= nextlevel();
}
Here is the calculations from the BattleManager class:
public void battleend() {
player.exp += expgain;
if (player.levelready()) {
print("You leveled up!");
player.levelup();
}
}
Now, the difficulty I'm having is that the nextlevel() method doesn't seem to always return the amount of exp required for the next level, it just returns 0. In the Room class I have a method that prints your stats to the screen.
The code is something like:
public void printstats() {
print("Level " + player.level);
print("EXP " + player.exp);
print("Next Level " + player.nextlevel());
}
Here is what's printed out before the battle:
Level 1
EXP 0
Next Level 1
Here is what's printed out after the battle:
Level 2
EXP 1
Next Level 0
Can somebody please help me with this? I would really appreciate it. Thank you!
I would like to thank Mahmoud Hossam for helping me figure out the problem. It turns out that the ^ operator in Java does not raise a number to a power but is a xor operator. Here's how I changed the method to fix the code!
public int nextlevel() {
double x = (double) level;
close = Math.round(4 * (Math.pow(x, 3)) / 5);
int next = (int) close;
return next;
}
tgdavies asked why I didn't just copy and paste the whole thing into here. This is because Room is currently over 500 lines, and I took out a bunch of unnecessary info from the method to make it easier to read. Here is the method in question:
String spc = "n\------";
public String STATS() {
String a = ("---Stats---\nHP" + dummy.curhp + "/" + dummy.maxhp + "n\Attack " + dummy.atktotal + "n\Defense" + dummy.deftotal);
a = (a + "n\Magick " + dummy.mgk + "n\Speed " + dummy.speed);
a = (a + spc + "n\Level " + dummy.level + "n\EXP " + dummy.exp + "Next Level " + dummy.nextlevel() + " EXP");
return a
}

How do I fix my looping for this Single Player Dice Game (4 - 4 sided die)? Issues with Scanner input not yielding correct outputs

// I've been working on this all day but still seem to be stuck.
// I'm not getting any obvious errors but the looping seems to be broken.
// I'm a beginner so its very likely I missed something big but just overlooked it.
// This assignment is due at midnight for my class lol.
// I feel like I constructed the base format decently however my unfamiliarity with using loops is really throwing me for one. I've looked online elsewhere but many of the "dice" programs people have made only pertain to one 6-sided die and do not involve a turn based user input.
// Any useful tips would be fantastic, is there a more efficient way to go about constructing this game? I know creating multiple classes would have cleaned up the look of the program but I'm really only looking for functionality at the moment.
package prgm06;
import java.util.Scanner;
public class DiceGame
{
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
System.out.println("Do you wish to play? [y,n]: ");
do { // I always want the dice to roll unless "n" is selected.
answer = stdIn.next();
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
}
while(answer.equalsIgnoreCase("y")); // issues with "y" not printing if/ else statements
{
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) && (d1 == d3) && (d1 == d4))
{
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
}
else
{
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
}
// do
{
answer = stdIn.next(); // I'm not sure if i need to keep using this at each segment
}
for(answer.equalsIgnoreCase("n");; // will not print on first user input of "n".
{
// System.out.println();
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
if (userWin > userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " Good Job!");
System.out.println(turnCounter + " Rounds played.");
}
else if (userWin < userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " You shouldn't bet money on this game...");
System.out.println(turnCounter + " Rounds played.");
}
else
{
System.out.println("Your win/loss ratio is: 1.0 .");
System.out.println(turnCounter + " Rounds played.");
}
break;
}
}
}
I've edited your code. Some errors were related to syntax, and some were possibly related to the logical flows. This should work as a base, and you can modify and improve it as you see fit:
import java.util.Scanner;
public class DiceGame {
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
do { // I always want the dice to roll unless "n" is selected.
System.out.println();
System.out.println("Do you wish to play? [y,n]: ");
answer = stdIn.next();
if (answer.equalsIgnoreCase("y")) {
turnCounter++;
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) || (d1 == d3) || (d1 == d4) || (d2 == d3) || (d2 == d4) || (d3 == d4) {
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
} else {
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
System.out.println("Your win/loss ratio is: " + userWin + ":" + userLose);
if (userWin > userLose) {System.out.println("Good Job!");}
if (userWin < userLose) {System.out.println("You shouldn't bet money on this game...");}
System.out.println(turnCounter + " Rounds played.");
}
} while(answer.equalsIgnoreCase("y"));
}
}
Some points to note:
The game will keep running as long as the user types in 'y', since that is your condition: answer.equalsIgnoreCase("y").
I changed the win condition logic to check for at least a pair using the logical OR operator
I removed the division operator for the ratio result for win/loss and just replaced it with a display of wins:losses; This could be changed if you want it to calculate for an actual percentage or decimal value, but you have to check for cases where losses == 0 to prevent a divide by zero error
The Do-While loop should encompass all of the gameplay from start to finish, so the question that asks you to play again should go at the start or at the end of this loop (I placed it at the start)

How to get my Java 'if' statement to work?

I am very new to learning Java and currently I am working on a program that lets me fight the computer based on simple stats that I have assigned us and a random number to function as a dice roll. I recognize that there may be numerous other problems with my code, but the main issue I am trying to resolve is the "Syntax error on tokens, delete these tokens" on line 84 and the "Syntax error, insert "}" to complete Statement" on line 77.
I don't see what the issue is. What am I doing wrong? Both issues are listed near the bottom of my code in comments next to their corresponding lines.
import java.util.Scanner;
import java.util.Random;
public class Fight {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name");
String you = keyboard.next();
int youWounds = 1;
int youTough = 4;
int youAttack = 1;
int youWS = 4;
int youAS = 3;
String Comp = "Bad Guy";
int compWounds = 1;
int compTough = 4;
int compAttack = 1;
int compWS = 4;
int compAS = 3;
System.out.println(you + ", do you want to FIGHT?!?!?");
System.out.println("Yes / No?");
String inputString = keyboard.next();
if (inputString.equalsIgnoreCase("Yes")) {
System.out.println("FIGHT!!!!");
while (youWounds > 0 && compWounds > 0) {
int youRan = new Random().nextInt(6)+1; // this is where you roll to hit
System.out.println(you + " rolls " + youRan +" to hit");
if (youRan >= 7-youWS) { // this is the logic for roll to hit
System.out.println(you +" hit");
int youRanTW = new Random().nextInt(6)+1; // this is where you check to see if your hit wounds
System.out.println(you + " rolls " + youRanTW +" to wound");
if (youRanTW > compTough) { // this is the logic for roll to wound
System.out.println(you+" wounds"+Comp);
compWounds = compWounds - 1; // this is where comp loses a wound
if (compWounds <= 0) { // this is the logic for wound loss
System.out.println(Comp+" dies!!!");
} else {
System.out.println("But, "+Comp+" fights on!");
}
} else {
System.out.println(you=" does not wound");
}
} else {
System.out.println(you +" misses");
}
int compRan = new Random().nextInt(6)+1;
System.out.println(Comp+" rolls " + compRan + " to hit");
if (compRan >= 7-compWS) { // this is the logic for roll to hit
System.out.println(Comp +" hit");
int compRanTW = new Random().nextInt(6)+1; // this is where you check to see if your hit wounds
System.out.println(Comp + " rolls " + compRanTW +" to wound");
if (compRanTW > youTough) { // this is the logic for roll to wound
System.out.println(Comp+" wounds"+you);
youWounds = youWounds - 1; // this is where you loses a wound
if (youWounds <= 0) { // this is the logic for wound loss
System.out.println(you+" dies!!!");
} else {
System.out.println("But, "+you+" fights on!");
}
} else {
System.out.println(Comp=" does not wound");
}
} else {
System.out.println(Comp +" misses");
}
} else { // this is wher I get "Syntax error, insert "}" to complete Statement". The "}" is underlined in red on my screen
if (youWounds <=0){
System.out.println(Comp+" WINS!!!!");
} else {
System.out.println(you+" WINS!!!!");
}
}
} else { // this is where i get "Syntax error on tokens, delete these tokens". it wants me to delete "} else".
System.out.println(you + " you are a looser!!!!!!!!");
}
keyboard.close();
}
}
There are a few issues with the flow of your program, but the current problem is that you are trying to use else on your while loop. This is not possible or necessary.
The while loop will continue until the defined condition is met. Once that happens, the while loop ends and the next line of code is executed.
So, remove the else { from the closing of the while loop. You can then just evaluate the results.
Here's the corrected code, with a couple comments to show WHERE to remove things:
import java.util.Random;
import java.util.Scanner;
public class Fight {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name");
String you = keyboard.next();
int youWounds = 1;
int youTough = 4;
int youAttack = 1;
int youWS = 4;
int youAS = 3;
String Comp = "Bad Guy";
int compWounds = 1;
int compTough = 4;
int compAttack = 1;
int compWS = 4;
int compAS = 3;
System.out.println(you + ", do you want to FIGHT?!?!?");
System.out.println("Yes / No?");
String inputString = keyboard.next();
if (inputString.equalsIgnoreCase("Yes")) {
System.out.println("FIGHT!!!!");
while (youWounds > 0 && compWounds > 0) {
int youRan = new Random().nextInt(6) + 1; // this is where you roll to hit
System.out.println(you + " rolls " + youRan + " to hit");
if (youRan >= 7 - youWS) { // this is the logic for roll to hit
System.out.println(you + " hit");
int youRanTW = new Random().nextInt(6) + 1; // this is where you check to see if your hit wounds
System.out.println(you + " rolls " + youRanTW + " to wound");
if (youRanTW > compTough) { // this is the logic for roll to wound
System.out.println(you + " wounds" + Comp);
compWounds = compWounds - 1; // this is where comp loses a wound
if (compWounds <= 0) { // this is the logic for wound loss
System.out.println(Comp + " dies!!!");
} else {
System.out.println("But, " + Comp + " fights on!");
}
} else {
System.out.println(you = " does not wound");
}
} else {
System.out.println(you + " misses");
}
int compRan = new Random().nextInt(6) + 1;
System.out.println(Comp + " rolls " + compRan + " to hit");
if (compRan >= 7 - compWS) { // this is the logic for roll to hit
System.out.println(Comp + " hit");
int compRanTW = new Random().nextInt(6) + 1; // this is where you check to see if your hit wounds
System.out.println(Comp + " rolls " + compRanTW + " to wound");
if (compRanTW > youTough) { // this is the logic for roll to wound
System.out.println(Comp + " wounds" + you);
youWounds = youWounds - 1; // this is where you loses a wound
if (youWounds <= 0) { // this is the logic for wound loss
System.out.println(you + " dies!!!");
} else {
System.out.println("But, " + you + " fights on!");
}
} else {
System.out.println(Comp = " does not wound");
}
} else {
System.out.println(Comp + " misses");
}
} // REMOVE THE ELSE AND BRACKET
if (youWounds <= 0) {
System.out.println(Comp + " WINS!!!!");
} else {
System.out.println(you + " WINS!!!!");
}
// REMOVE THIS BRACKET
} else { // this is where i get "Syntax error on tokens, delete these tokens". it wants me to delete "} else".
System.out.println(you + " you are a looser!!!!!!!!");
}
keyboard.close();
}
}

Multi Threading - Request input once for all variables (Java)

Below are codes and outputs for a multithreading function whereby there is a counter and functions of add, subtract, multiply and divide. I'm using Eclipse.
4 Threads for each mathematical function:
public class Maths {
public static void main(String args[]){
CalculationThread T1 = new CalculationThread("Addition");
T1.start();
CalculationThread T2 = new CalculationThread("Subtraction");
T2.start();
CalculationThread T3 = new CalculationThread("Multiplication");
T3.start();
CalculationThread T4 = new CalculationThread("Division");
T4.start();
}
}
class CalculationThread extends Thread{
private Thread t;
private String maths;
private int count = 0;
private int resultplus, resultminus, resulttimes, resultdivide = 0;
CalculationThread(String answer){
maths = answer;
}
public void start(){
System.out.println("Starting calculation of " + maths + "\n");
if(t == null){
t = new Thread (this, maths);
t.start();
}
}
Here is where the functions take place, it will use the counters as 2 numbers to perform an equation.
public void run(){
try {
for (int x=0; x<=3 ; x++){
if(maths == "Addition"){
System.out.println("Calculating: " + maths + " of " + count +
" + "+ count + " = " + resultplus + "\n");
Thread.sleep(3000);
count++;
resultplus = count + count;
}
else if(maths == "Subtraction"){
System.out.println("Calculating: " + maths + " of " + count +
" - "+ count + " = " + resultminus + "\n");
Thread.sleep(3000);
count++;
resultminus = count - count;
}
else if(maths == "Multiplication"){
System.out.println("Calculating: " + maths + " of " + count +
" * "+ count + " = " + resulttimes + "\n");
Thread.sleep(3000);
count++;
resulttimes = count * count;
}
else if(maths == "Division"){
System.out.println("Calculating: " + maths + " of " + count +
" / "+ count + " = " + resultdivide + "\n");
Thread.sleep(3000);
count++;
resultdivide = count / count;
}
}
}
catch (InterruptedException e){
System.out.println("Math function failed");
}
if(maths == "Addition"){
System.out.println("Addition completed.");
}
else if(maths == "Subtraction"){
System.out.println("Subtraction completed.");
}
else if(maths == "Multiplication"){
System.out.println("Multiplication completed.");
}
else if(maths == "Division"){
System.out.println("Division completed.");
}
}
}
The output:
Starting calculation of Addition
Starting calculation of Subtraction
Calculating: Addition of 0 + 0 = 0
Starting calculation of Multiplication
Calculating: Subtraction of 0 - 0 = 0
Starting calculation of Division
Calculating: Multiplication of 0 * 0 = 0
Calculating: Division of 0 / 0 = 0
Calculating: Subtraction of 1 - 1 = 0
Calculating: Addition of 1 + 1 = 2
Calculating: Multiplication of 1 * 1 = 1
Calculating: Division of 1 / 1 = 1
Calculating: Addition of 2 + 2 = 4
Calculating: Subtraction of 2 - 2 = 0
Calculating: Division of 2 / 2 = 1
Calculating: Multiplication of 2 * 2 = 4
Calculating: Subtraction of 3 - 3 = 0
Calculating: Addition of 3 + 3 = 6
Calculating: Division of 3 / 3 = 1
Calculating: Multiplication of 3 * 3 = 9
Subtraction completed.
Addition completed.
Division completed.
Multiplication completed.
The code above works whereby all 4 functions will be done simultaneously , but whenever I try including a JOptionPane for user input instead of an automatic counter, each of the 4 threads will request at a time. Thus its not counted as multithreading if the functions are waiting for me to input 2 numbers. How and in what way can I include a user input that only requires user to input at the beginning so that all functions can use the 2 variables.
I'm not sure if I understood it correctly.
If you just want to block the calculation threads and wait for an initial user Input you can use a Semaphore.
The UI Thread that waits for the user input shows the dialog and releases the waiting calculation threads by setting the number of permits / threads.
Here is an example how this could look like (it also uses an more object oriented approach). For simplicity, I've skipped the Multiplication and Division Tasks
import java.util.concurrent.Semaphore;
import javax.swing.JOptionPane;
public class MathSample {
// because updated / read from different threads mark as volatile
private volatile int a, b;
// semaphore with no initial permits i.e.
// the calculations will wait until permits are available.
private Semaphore available = new Semaphore(0);
private abstract class Task implements Runnable {
public abstract void doCalculation();
public abstract String getName();
#Override
public void run() {
try {
// wait until a permit becomes available
available.acquire();
// not sure what should happen here
// wait again for user input?
for (int x = 0; x < 50; ++x) {
a = a + x;
doCalculation();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(String.format("Task %s completed.", getName()));
}
}
private class AdditionTask extends Task {
public void doCalculation() {
System.out.println(String.format("Calculating: Addition of + %d + %d = %d", a, b, a+b));
}
public String getName() {
return "Addition";
}
}
private class SubstractionTask extends Task {
public void doCalculation() {
System.out.println(String.format("Calculating: Substraction of + %d - %d = %d", a, b, a-b));
}
public String getName() {
return "Substraction";
}
}
private void run() {
new Thread(new AdditionTask()).start();
new Thread(new SubstractionTask()).start();
a = Integer.parseInt(JOptionPane.showInputDialog("First value"));
b = Integer.parseInt(JOptionPane.showInputDialog("Second value"));
available.release(2); // let the 2 calculation threads run
}
public static void main(String ...args) {
new MathSample().run();
}
}
As you can see you don't have to overwrite the start method of the Thread to run a different thread.
Your start method of your CalculationThread is at least strange because you overwrite the start method of the Thread class and within that you create another Thread instance where you pass your CalculationThread as Runnable.
Easier / better:
class Calculation implements Runnable {
...
#override
public void run() {
// the name you passed to the thread is your math
// lets get it from the currently running thread where it is stored.
final String math = Thread.currentThread().getName();
...
}
}
// somewhere else
new Thread(new CalculationThread, math).start();
You can refer following codes.
Maybe it will suit your needs according to my understanding on your question. I also applied .equals() to the code according to Hovercraft Full Of Eels suggestion.
import javax.swing.JOptionPane;
public class Maths {
public static void main(String[] args) {
// TODO Auto-generated method stub
String num1 = JOptionPane.showInputDialog("Num1: ");
String num2 = JOptionPane.showInputDialog("Num2: ");
int num11 = Integer.parseInt(num1);
int num22 = Integer.parseInt(num2);
calculationThread T1 = new calculationThread("Addition");
T1.getNumber(num11, num22);
T1.start();
calculationThread T2 = new calculationThread("Subtraction");
T2.getNumber(num11, num22);
T2.start();
calculationThread T3 = new calculationThread("Multiplication");
T3.getNumber(num11, num22);
T3.start();
calculationThread T4 = new calculationThread("Division");
T4.getNumber(num11, num22);
T4.start();
}
}
class calculationThread extends Thread{
private Thread t;
private String maths;
private int a;
private int b;
private int resultplus = 0;
private int resultminus = 0;
private int resulttimes = 0;
private int resultdivide = 0;
public void getNumber(int num1, int num2){
a = num1;
b = num2;
}
calculationThread(String answer){
maths = answer;
}
public void start(){
System.out.println("Starting calculation of " + maths + "\n");
if(t == null){
t = new Thread(this, maths);
t.start();
}
}
public void run(){
try {
for (int x=0; x<=3 ; x++){
if(maths.equals("Addition")){
System.out.println("Calculating: " + maths + " of " + a +
" + "+ b + " = " + resultplus + "\n");
Thread.sleep(3000);
resultplus = a + b;
}
else if(maths.equals("Subtraction")){
System.out.println("Calculating: " + maths + " of " + a +
" - "+ b + " = " + resultminus + "\n");
Thread.sleep(3000);
resultminus = a - b;
}
else if(maths.equals("Multiplication")){
System.out.println("Calculating: " + maths + " of " + a +
" * "+ b + " = " + resulttimes + "\n");
Thread.sleep(3000);
resulttimes = a * b;
}
else if(maths.equals("Division")){
System.out.println("Calculating: " + maths + " of " + a +
" / "+ b + " = " + resultdivide + "\n");
Thread.sleep(3000);
resultdivide = a / b;
}
}
}
catch (InterruptedException e){
System.out.println("Math function failed");
}
finally{
if(maths.equals("Addition")){
System.out.println("Addition completed.");
}
else if(maths.equals("Subtraction")){
System.out.println("Subtraction completed.");
}
else if(maths.equals("Multiplication")){
System.out.println("Multiplication completed.");
}
else if(maths.equals("Division")){
System.out.println("Division completed.");
}
}
}
}

My event handler keeps reporting an error on my overloaded methods

I'm using Java, and I'm trying to call an overloaded method in an event handler. calculateCost() and calculateCost(int,boolean) are the methods I'm overloading, now.
This is the calculateCost(int,boolean) along with the calculateCost() method below:
public double calculateCost() { //calculates cost of computer &peripherals.
if (printerCB.isSelected()) {
return baseComputer() + printer();
}
if (dellMouseCB.isSelected()) {
return baseComputer() + dellMouse();
}
if (logiKeyboardCB.isSelected()) {
return baseComputer() + logiKeyboard();
}
if (canonScannerCB.isSelected()) {
return baseComputer() + canonScanner();
}
if (razerMouseCB.isSelected()) {
return baseComputer() + razerMouse();
}
if (razerKeyboardCB.isSelected()) {
return baseComputer() + razerKeyboard();
}
return baseComputer();
}
public double claculateCost(int quant, boolean shipp) { //calculates the shipping rate for the computer, &peripherals.
quant = 1;
double total = calculateCost();
if (groundShipRB.isSelected() || airShipRB.isSelected() || fedExRB.isSelected()) {
shipp = true;
if (shipp == true) {
{
if (groundShipRB.isSelected()) {
while (quant >= 100) {
return calculateCost() * 0.05;
}
}
if (airShipRB.isSelected()) {
return calculateCost() * 0.10;
}
if (fedExRB.isSelected()) {
return calculateCost() * 0.20;
}
}
}
}
return 0;
}
This is the Code inside the event handler:
private void costCalcWShipButtonActionPerformed(java.awt.event.ActionEvent evt) {
int quant = 1;
double dsqnt = 0.00;
double cost = calculateCost();
boolean shipp = false;
double rate = calculateCost(quant, shipp);
outputTextPane.setText("");
outputTextPane.setText(outputTextPane.getText() + "Quantity." + "\t\t" + "Price." + "\t\t" + "Shipping rate" + "\t\t" + "Quantity discount(per $100)." + "\n");
outputTextPane.setText(outputTextPane.getText() + quant + "\t\t" + cost * quant + "\t\t" + rate + "\t\t" + discountPercentage(quant, dsqnt) + "\n");
for (quant = 100; quant <= 1000; quant = quant + 100) {
outputTextPane.setText(outputTextPane.getText() + quant + "\t\t" + cost * quant + "\t\t" + rate + "\t\t" + discountPercentage(quant, dsqnt) + "\n");
}
}
The calculateCost() method works when I put it into the event handler for the GUI, but when I try calling the calculateCost(int,boolean) it gives me this error:
error: method calculateCost in class compCostCalc cannot be applied to given types;
int quant=1;double dsqnt=0.00;double cost=calculateCost();boolean shipp=false;double rate=calculateCost(quant,shipp);
required: no arguments
found: int,boolean
reason: actual and formal argument lists differ in length
1 error.
This has confused me for a while, any feedback I can get to get it to work?
There's a typo in your code: claculateCost instead of calculateCost (in the method definition).

Categories