Drops being cleared, but still dropping - java

So I am making a plugin, and everything works so far.
The only problem I have is that the chestplate lore wipes, and items sometimes drop twice, one with broken durability and the same stats. Any help is appreciated
package me.impatheimpaler.mmo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Mobdrops extends JavaPlugin implements Listener {
public List<String> t1h = new ArrayList<String>();
public List<String> t1c = new ArrayList<String>();
public List<String> t1l = new ArrayList<String>();
public List<String> t1b = new ArrayList<String>();
public List<String> t1s = new ArrayList<String>();
public static me.impatheimpaler.mmo.Main plugin;
public Mobdrops(Main main) {
plugin = main;
}
#EventHandler
public void onDeath(EntityDeathEvent e) {
Skeleton s = (Skeleton) e.getEntity();
if (!(e.getEntity() instanceof Player)) {
e.getDrops().clear();
e.setDroppedExp(0);
}
if ((e.getEntity() instanceof Skeleton)) {
Skeleton sk = (Skeleton)e.getEntity();
if (sk.getCustomName() == null) {
return;
}
}
Random random = new Random();
int rarity = random.nextInt(3) + 1;
int chestdrop = random.nextInt(20) + 1;
int legsdrop = random.nextInt(17) + 1;
int helmdrop = random.nextInt(6) + 1;
int bootsdrop = random.nextInt(11) + 1;
int swordDrop = random.nextInt(15) + 1;
if (helmdrop == 3) {
ItemStack t1helm = new ItemStack(Material.LEATHER_HELMET);
ItemMeta t1helmMeta = t1helm.getItemMeta();
t1helmMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Helmet");
if (rarity == 3) {
int hp = random.nextInt(20) + 33;
t1h.add(ChatColor.RED + "HP: +" + hp);
t1h.add(ChatColor.GOLD + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(10) + 20;
t1h.add(ChatColor.RED + "HP: +" + hp);
t1h.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(15) + 6;
t1h.add(ChatColor.RED + "HP: +" + hp);
t1h.add(ChatColor.GRAY + "Poor");
}
t1helmMeta.setLore(t1h);
t1helm.setItemMeta(t1helmMeta);
s.getEquipment().setHelmet(t1helm);
e.getDrops().add(t1helm);
t1h.clear();
}
if (chestdrop == 7) {
ItemStack t1chest = new ItemStack(Material.LEATHER_CHESTPLATE);
ItemMeta t1chestMeta = t1chest.getItemMeta();
t1chestMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Chestplate");
if (rarity == 3) {
int hp = random.nextInt(20) + 72;
t1c.add(ChatColor.RED + "HP: +" + hp);
t1c.add(ChatColor.GOLD + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(30) + 33;
t1c.add(ChatColor.RED + "HP: +" + hp);
t1c.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(10) + 20;
t1c.add(ChatColor.RED + "HP: +" + hp);
t1c.add(ChatColor.GRAY + "Poor");
}
t1chestMeta.setLore(t1c);
t1chest.setItemMeta(t1chestMeta);
s.getEquipment().setChestplate(t1chest);
e.getDrops().add(t1chest);
t1c.clear();
}
if (legsdrop == 2) {
ItemStack t1legs = new ItemStack(Material.LEATHER_LEGGINGS);
ItemMeta t1legsMeta = t1legs.getItemMeta();
t1legsMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Leggings");
if (rarity == 3) {
int hp = random.nextInt(20) + 61;
t1l.add(ChatColor.RED + "HP: +" + hp);
t1l.add(ChatColor.YELLOW + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(20) + 33;
t1l.add(ChatColor.RED + "HP: +" + hp);
t1l.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(10) + 10;
t1l.add(ChatColor.RED + "HP: +" + hp);
t1l.add(ChatColor.GRAY + "Poor");
}
t1legsMeta.setLore(t1l);
t1legs.setItemMeta(t1legsMeta);
s.getEquipment().setLeggings(t1legs);
e.getDrops().add(t1legs);
t1l.clear();
}
if (bootsdrop == 1) {
ItemStack t1boots = new ItemStack(Material.LEATHER_BOOTS);
ItemMeta t1bootsMeta = t1boots.getItemMeta();
t1bootsMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Boots");
if (rarity == 3) {
int hp = random.nextInt(20) + 23;
t1b.add(ChatColor.RED + "HP: +" + hp);
t1b.add(ChatColor.YELLOW + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(10) + 10;
t1b.add(ChatColor.RED + "HP: +" + hp);
t1b.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(5) + 6;
t1b.add(ChatColor.RED + "HP: +" + hp);
t1b.add(ChatColor.GRAY + "Poor");
}
t1bootsMeta.setLore(t1b);
t1boots.setItemMeta(t1bootsMeta);
s.getEquipment().setBoots(t1boots);
e.getDrops().add(t1boots);
t1b.clear();
}
if (swordDrop == 3) {
ItemStack t1sword = new ItemStack(Material.WOOD_SWORD);
ItemMeta t1swordMeta = t1sword.getItemMeta();
if (rarity == 3) {
int min = random.nextInt(20) + 11;
int max = random.nextInt(20) + 21;
t1s.add(ChatColor.RED + "DMG: " + min + " - " + max);
t1s.add(ChatColor.YELLOW + "Legendary");
}
if (rarity == 2) {
int max = random.nextInt(10) + 21;
int min = random.nextInt(10) + 11;
t1s.add(ChatColor.RED + "DMG: " + min + " - " + max);
t1s.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int min = random.nextInt(5) + 6;
int max = random.nextInt(10) + 11;
t1s.add(ChatColor.RED + "DMG: " + min + " - " + max);
t1s.add(ChatColor.GRAY + "Poor");
}
t1swordMeta.setLore(t1s);
t1sword.setItemMeta(t1swordMeta);
s.getEquipment().setItemInHand(t1sword);
e.getDrops().add(t1sword);
t1s.clear();
}
}
}

There are quite a few issues here, but I think the reason you are seeing duplicate items is because you are adding it to both the drop list as well as an equipment slot. When a mob has an item equipped it has a small chance of dropping that item. So essentially you are adding the item twice and occasionally one extra is dropping. Also, code formatting and readability is huge if you ever want to expand on this.
I don't normally do this, but I wanted to help you out. I'm doing this in notepad so please bare with any small errors. If there are any small mistakes let me know so I can update the code accordingly.
package me.impatheimpaler.mmo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Mobdrops extends JavaPlugin implements Listener {
public static me.impatheimpaler.mmo.Main plugin;
public Mobdrops(Main main) {
plugin = main;
}
private ItemStack AddArmorToDropList(EntityDeathEvent e, Material oMaterial, String strItemName, int intRarity, int T3Random, int T3Bonus, int T2Random, int T2Bonus, int T1Random, int T1Bonus) {
ItemStack oItemStack = new ItemStack(oMaterial);
ItemMeta oItemMeta = oItemStack.getItemMeta();
oItemMeta.setDisplayName(strItemName);
List<String> arrItemLore = new ArrayList<String>(); //Always use descriptive variable names
Random random = new Random();
if (intRarity == 3) {
arrItemLore.add(ChatColor.RED + "HP: +" + (random.nextInt(T3Random) + T3Bonus));
arrItemLore.add(ChatColor.GOLD + "Legendary");
}
else if (intRarity == 2) {
arrItemLore.add(ChatColor.RED + "HP: +" + ()random.nextInt(T2Random) + T2Bonus);
arrItemLore.add(ChatColor.AQUA + "Normal");
}
else { //Always use a final else to catch all exceptions
arrItemLore.add(ChatColor.RED + "HP: +" + (random.nextInt(T1Random) + T1Bonus));
arrItemLore.add(ChatColor.GRAY + "Poor");
}
oItemMeta.setLore(arrItemLore);
oItemStack.setItemMeta(oItemMeta);
e.getDrops().add(oItemStack);
}
private void AddWeaponToDropList(EntityDeathEvent e, Material oMaterial, String strItemName, int intRarity, int T3MinDmg, int T3MaxDmg, int T2MinDmg, int T2MaxDmg, int T1MinDmg, int T1MaxDmg) {
ItemStack oItemStack = new ItemStack(oMaterial);
ItemMeta oItemMeta = oItemStack.getItemMeta();
oItemMeta.setDisplayName(strItemName);
List<String> arrItemLore = new ArrayList<String>(); //Always use descriptive variable names
Random random = new Random();
if (intRarity == 3) {
arrItemLore.add(ChatColor.RED + "DMG: " + T3MinDmg + " - " + T3MaxDmg);
arrItemLore.add(ChatColor.GOLD + "Legendary");
}
else if (intRarity == 2) {
arrItemLore.add(ChatColor.RED + "DMG: " + T2MinDmg + " - " + T2MaxDmg);
arrItemLore.add(ChatColor.AQUA + "Normal");
}
else { //Always use a final else to catch all exceptions
arrItemLore.add(ChatColor.RED + "DMG: " + T1MinDmg + " - " + T1MaxDmg);
arrItemLore.add(ChatColor.GRAY + "Poor");
}
oItemMeta.setLore(arrItemLore);
oItemStack.setItemMeta(oItemMeta);
e.getDrops().add(oItemStack);
}
#EventHandler
public void onDeath(EntityDeathEvent e) {
Skeleton oSkeleton = null; //Never do a direct cast without being sure that the entity is what you think it is
if (!(e.getEntity() instanceof Player)) { //Clear items and exp dropped
e.getDrops().clear();
e.setDroppedExp(0);
}
if (e.getEntity() instanceof Skeleton) {
if (oSkeleton.getCustomName() != null) {
oSkeleton = (Skeleton) e.getEntity(); //Set oSkeleton value
}
}
if (oSkeleton != null) {
Random random = new Random();
int intRarity = random.nextInt(3) + 1;
if ((random.nextInt(6) + 1) == 3) {
AddArmorToDropList(e, Material.LEATHER_HELMET, ChatColor.WHITE + "Renegade's Torn Helmet", intRarity, 20, 33, 10, 20, 15, 6);
}
if ((random.nextInt(20) + 1) == 7) {
AddArmorToDropList(e, Material.LEATHER_CHESTPLATE, ChatColor.WHITE + "Renegade's Torn Chestplate", intRarity, 20, 72, 30, 33, 10, 20);
}
if ((random.nextInt(17) + 1) == 2) {
AddArmorToDropList(e, Material.LEATHER_LEGGINGS, ChatColor.WHITE + "Renegade's Torn Leggings", intRarity, 20, 61, 20, 33, 10, 10);
}
if ((random.nextInt(11) + 1) == 1) {
AddArmorToDropList(e, Material.LEATHER_BOOTS, ChatColor.WHITE + "Renegade's Torn Boots", intRarity, 20, 23, 10, 10, 5, 6);
}
if ((random.nextInt(15) + 1) == 3) {
int intT3Min = random.nextInt(20) + 11;
int intT3Max = random.nextInt(20) + 21;
int intT2Min = random.nextInt(10) + 11;
int intT2Max = random.nextInt(10) + 21;
int intT1Min = random.nextInt(5) + 6;
int intT1Max = random.nextInt(10) + 11;
AddWeaponToDropList(e, Material.WOOD_SWORD, ChatColor.WHITE + "RGAMinecraft's Sword", intRarity, intT3Min, intT2Max, intT2Min, intT3Max, intT1Min, intT1Max);
}
}
}
}

Related

Why I can't get medium level for math questions to appear?

import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.border.*;
import java.awt.event.*;
public class MATHfighter extends JFrame implements ActionListener
{
Border border = new LineBorder(Color.WHITE, 3, true);
Border unborder = new LineBorder(Color.BLACK, 1, true);
Container c = getContentPane();
JPanel gameText = new JPanel();
JPanel gameMenu = new JPanel();
JTextField answer = new JTextField(12);
JTextField result = new JTextField(12);
JButton bAnswer = new JButton("Answer");
JButton bNext = new JButton("Next");
JButton bExit = new JButton("Exit");
int score = 0;
JLabel mathQuestion = new JLabel();
JLabel startText = new JLabel(">");
JLabel startText1 = new JLabel(">");
Font headlineFont = new Font("Comic Sans MS",Font.BOLD, 15);
int typeQ;
int number1;
int number2;
int number3;
int life_point = 200;
int player_lp = 200;
int r = 0;
int g = 204;
int b = 0;
int r1 = 0;
int g1 = 204;
int b1 = 0;
public MATHfighter()
{
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setBackground(Color.BLACK);
textGame();
menuGame();
bAnswer.addActionListener(this);
bNext.addActionListener(this);
bExit.addActionListener(this);
}
public void textGame()
{
gameText.setLayout(null);
gameText.setBorder(border);
gameText.setBounds(10,410,290,140);
gameText.setVisible(true);
gameText.setBackground(Color.BLACK);
gameText.add(startText);
gameText.add(startText1);
startText.setForeground(Color.WHITE);
startText1.setForeground(Color.WHITE);
startText.setFont(headlineFont);
startText1.setFont(headlineFont);
add(gameText);
randomMath();
}
public void menuGame()
{
gameMenu.setLayout(null);
gameMenu.setBorder(border);
gameMenu.setBounds(305,410,290,140);
gameMenu.setVisible(true);
gameMenu.setBackground(Color.BLACK);
add(gameMenu);
gameMenu.add(bAnswer);
bAnswer.setBorder(border);
bAnswer.setBackground(Color.BLACK);
bAnswer.setFont(headlineFont);
bAnswer.setForeground(Color.WHITE);
bAnswer.setBounds(10,10,130,50);
gameMenu.add(bNext);
bNext.setBorder(border);
bNext.setBackground(Color.BLACK);
bNext.setFont(headlineFont);
bNext.setForeground(Color.WHITE);
bNext.setBounds(150,10,130,50);
bNext.setEnabled(false);
gameMenu.add(bExit);
bExit.setBorder(border);
bExit.setBackground(Color.BLACK);
bExit.setFont(headlineFont);
bExit.setForeground(Color.WHITE);
bExit.setBounds(150,70,130,50);
}
public void randomMath()
{
typeQ = (int) (Math.random() * 4) + 1;
number1 = (int) (Math.random() * 10) + 10;
number2 = (int) (Math.random() * 10) + 10;
number3 = (int) (Math.random() * 10) + 10;
mathQuestion.setFont(headlineFont);
mathQuestion.setBounds(10,10,290,15);
mathQuestion.setForeground(Color.WHITE);
gameText.add(mathQuestion);
answer.setFont(headlineFont);
answer.setBorder(unborder);
answer.setBackground(Color.BLACK);
answer.setForeground(Color.WHITE);
startText.setBounds(10,35,20,20);
answer.setBounds(25,35,250,20);
gameText.add(answer);
result.setFont(headlineFont);
result.setBorder(unborder);
result.setBackground(Color.BLACK);
result.setForeground(Color.WHITE);
result.setBounds(25,65,250,20);
result.setEditable(false);
startText1.setBounds(10,65,20,20);
gameText.add(result);
if((life_point<=200)&&(life_point>100))
{
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " + " + number2 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " - " + number2 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " ?");
}
}
else if(life_point<=100)
{
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " + " + number3 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " - " + number3 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " + " + number3 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " - " + number3 + " ?");
}
}
}
public void paint(Graphics gr)
{
Color c1 = new Color(r, g, b);
Color c2 = new Color(r1, g1, b1);
super.paint(gr);
gr.setColor(c1);
gr.fillRect(212, 40, life_point, 30);
gr.setColor(c2);
gr.fillRect(212, 400, player_lp, 30);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bAnswer)
{
try
{
int kotae = Integer.parseInt(answer.getText());
if((life_point<=200)&&(life_point>100))
{
if(typeQ==1)
{
if ((number1 + number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 + number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==2)
{
if ((number1 - number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 - number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==3)
{
if ((number1 * number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==4)
{
if ((number1*number2 / number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
}
if(life_point<=100)
{
if(typeQ==1)
{
if ((number1 * number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==2)
{
if ((number1 * number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==3)
{
if ((number1*number2 / number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==4)
{
if ((number1*number2 / number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"<html><font face='Comic Sans MS' size='3'>INTEGER ONLY, KIDDO");
}
}
else if(e.getSource()==bNext)
{
typeQ = (int) (Math.random() * 4) + 1;
number1 = (int) (Math.random() * 10) + 10;
number2 = (int) (Math.random() * 10) + 10;
result.setText("");
answer.setText("");
answer.setEditable(true);
bNext.setEnabled(false);
bAnswer.setEnabled(true);
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " + " + number2 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " - " + number2 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " ?");
}
}
else
{
System.exit(0);
}
}
public static void main(String[] args)
{
MATHfighter fight = new MATHfighter();
fight.setSize(625,600);
fight.setVisible(true);
}
}
This is the continuation from my last question and I did change while loop to if-else, thank you to others who helped me.
My new problems are that I want a bunch of middle level questions to appear when enemy life point become 100 and below but the problem is my GUI became like this after I answered the fifth question:
there is a chance that my mathQuestion.setText are not working after I used these code:
else if(life_point<=100)
{
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " + " + number3 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " - " + number3 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " + " + number3 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " - " + number3 + " ?");
}
}
and
if(life_point<=100)
{
if(typeQ==1)
{
if ((number1 * number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==2)
{
if ((number1 * number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==3)
{
if ((number1*number2 / number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==4)
{
if ((number1*number2 / number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
I really hope that someone can help me about these problem
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container and the Performing Custom Painting sections.
The code provided in the question is typical of beginner Java programmers. All of the code is contained in one class. Almost all of the variables are class variables. Some of the variables are poorly named. Code is copied over and over with minor changes.
Swing layout managers are not used. Null layouts and absolute positioning are used instead. The makes for a brittle GUI that's hard to maintain and understand. I wonder how much effort it took to calculate all of the Swing component offsets?
So, let's see what we can do to improve this code. Here's the GUI I came up with.
Explanation
Breaking up the code into an application model, a view, and multiple ActionListeners helps me to separate my concerns and focus on one part of the application at a time.
Model
The first thing I did was create an application model class, the MathFighterModel class
The MathFighterModel class is a plain Java getter/setter class. It turned out that the class only needed three class variables; the answer to the current math problem, the number of enemy life points, and the number of player life points.
The creation of a math equation is contained in the generateRandomMathQuestion method. I calculate the correct answer and build the question String in the same method. This way, it's much easier to visually verify that the actual calculation matches the question String.
By the way, the code is doing integer division when it divides.
The rest of the class is getters and setters. The original code didn't include a check for either the enemy or player getting to zero life points. I didn't include the check either.
View
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
I used a JFrame. I did not extend a JFrame. The only reason you extend a Swing component, or any Java class, is to override one or more of the class methods. The JFrame has a default BorderLayout, which I used to place two JPanels.
I created four JPanels; a drawing JPanel for the health bars, a control JPanel, an entry JPanel, and a button JPanel. This allows me to separate my concerns and focus on one small part of the GUI at a time.
I create the drawing JPanel in a separate class. I extend JPanel because I override the paintComponent method. I call the super.paintComponent in the first line of the method to maintain the Swing paint chain.
I calculate the bar colors in the drawing JPanel. I also centered the bar drawings in the drawing JPanel. Finally, I added the life points number to the center of the bars.
The control JPanel is a container that holds the entry JPanel and the button JPanel. I used a FlowLayout to put the two JPanels side by side.
The entry JPanel contains the entry and display Swing components. I used a GridBagLayout to layout the ">" and the display and entry Swing components. Yes, the GridBagLayout looks complicated, but it's the easiest way to create a form with labels in one column and the entry fields in another column.
The button JPanel contains the JButtons. I used a GridLayout to arrange the JButtons. Yes, I had to put a dummy JLabel in column 1, row 2 to make the layout work.
Using Swing layout managers makes the GUI more flexible and allows for the easier addition of Swing components. Just maximize the GUI to see what happens.
Controller
I created three ActionListeners for the three JButtons. It's much easier to manage separate ActionListeners than one complicated ActionListener.
I used lambda expressions for the next button and exit button because they were simple ActionListeners. A lambda expression creates an anonymous ActionListener class under the covers.
I left the answer button ActionListener as an internal method to the view class. You can see how simple the method is, after creating an application model and view.
Code
Here's the complete runnable code. I made all the additional classes inner classes so I could post the code as one block. You should separate these classes into separate files.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
public class MathFighter implements ActionListener, Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new MathFighter());
}
private final DrawingPanel drawingPanel;
private JFrame frame;
private JLabel mathQuestionLabel, responseLabel;
private JTextField answerField;
private final MathFighterModel model;
public MathFighter() {
this.model = new MathFighterModel();
this.drawingPanel = new DrawingPanel(model);
}
#Override
public void run() {
frame = new JFrame("Math Fighter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(drawingPanel, BorderLayout.CENTER);
frame.add(createControlPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createControlPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBackground(Color.BLACK);
panel.add(createEntryPanel());
panel.add(createButtonPanel());
return panel;
}
private JPanel createEntryPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(Color.BLACK);
panel.setPreferredSize(new Dimension(300, 150));
Border outsideBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border insideBorder = BorderFactory.createLineBorder(Color.WHITE, 3);
panel.setBorder(BorderFactory.createCompoundBorder(outsideBorder,
insideBorder));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.insets = new Insets(10, 10, 10, 0);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.0;
panel.add(createLabel(">"), gbc);
gbc.gridx++;
gbc.weightx = 1.0;
mathQuestionLabel = createLabel(" ");
panel.add(mathQuestionLabel, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.weightx = 0.0;
panel.add(createLabel(">"), gbc);
gbc.gridx++;
gbc.weightx = 1.0;
answerField = new JTextField(12);
answerField.setFont(getHeadlineFont());
answerField.setBorder(BorderFactory.createEmptyBorder(0, -8, 0, 0));
answerField.setBackground(Color.BLACK);
answerField.setForeground(Color.WHITE);
panel.add(answerField, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.weightx = 0.0;
panel.add(createLabel(">"), gbc);
gbc.gridx++;
gbc.weightx = 1.0;
responseLabel = createLabel(" ");
panel.add(responseLabel, gbc);
updateEntryPanel();
return panel;
}
private JLabel createLabel(String labelText) {
JLabel label = new JLabel(labelText);
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
label.setFont(getHeadlineFont());
return label;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(0, 2, 10, 10));
panel.setBackground(Color.BLACK);
panel.setPreferredSize(new Dimension(300, 150));
Border outsideBorder = BorderFactory.createEmptyBorder(5, 0, 5, 5);
Border insideBorder = BorderFactory.createLineBorder(Color.WHITE, 3);
Border marginBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10);
Border compoundBorder = BorderFactory.createCompoundBorder(insideBorder,
marginBorder);
panel.setBorder(BorderFactory.createCompoundBorder(outsideBorder,
compoundBorder));
JButton answerButton = createButton("Answer", insideBorder);
answerButton.addActionListener(this);
panel.add(answerButton);
JButton nextButton = createButton("Next", insideBorder);
nextButton.addActionListener(event -> {
updateEntryPanel();
});
panel.add(nextButton);
panel.add(new JLabel(" "));
JButton exitButton = createButton("Exit", insideBorder);
exitButton.addActionListener(event -> {
frame.dispose();
System.exit(0);
});
panel.add(exitButton);
return panel;
}
private JButton createButton(String buttonText, Border insideBorder) {
JButton button = new JButton(buttonText);
button.setBorder(insideBorder);
button.setBackground(Color.BLACK);
button.setFont(getHeadlineFont());
button.setForeground(Color.WHITE);
return button;
}
private Font getHeadlineFont() {
return new Font("Comic Sans MS", Font.BOLD, 16);
}
public void updateEntryPanel() {
mathQuestionLabel.setText(model.generateRandomMathQuestion());
answerField.setText(" ");
answerField.requestFocusInWindow();
responseLabel.setText(" ");
}
public void repaint() {
drawingPanel.repaint();
}
#Override
public void actionPerformed(ActionEvent event) {
try {
int userAnswer = Integer.valueOf(answerField.getText().trim());
if (model.isAnswerCorrect(userAnswer)) {
responseLabel.setText("Correct");
model.incrementPlayerLife(20);
} else {
responseLabel.setText("Incorrect, try another answer");
model.incrementPlayerLife(-20);
}
answerField.requestFocusInWindow();
repaint();
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"<html><font face='Comic Sans MS' size='3'>INTEGER ONLY, KIDDO");
}
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final MathFighterModel model;
public DrawingPanel(MathFighterModel model) {
this.model = model;
this.setBackground(Color.BLACK);
this.setPreferredSize(new Dimension(400, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(getHeadlineFont());
int width = getWidth();
int height = getHeight();
int margin = 20;
int barHeight = 30;
int enemyLifePoints = model.getEnemyLifePoints();
g2d.setColor(calculateBarColor(enemyLifePoints));
int x = (width - enemyLifePoints) / 2;
int y = margin;
g2d.fillRect(x, y, enemyLifePoints, barHeight);
drawString(g2d, x, y, enemyLifePoints, barHeight);
int playerLifePoints = model.getPlayerLifePoints();
g2d.setColor(calculateBarColor(playerLifePoints));
x = (width - playerLifePoints) / 2;
y = height - margin - barHeight;
g2d.fillRect(x, y, playerLifePoints, barHeight);
drawString(g2d, x, y, playerLifePoints, barHeight);
}
private void drawString(Graphics2D g2d, int x, int y, int width,
int height) {
String lifePointString = Integer.toString(width);
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r = fm.getStringBounds(lifePointString, g2d);
int a = (width - (int) r.getWidth()) / 2 + x;
int b = (height - (int) r.getHeight()) / 2 + fm.getAscent() + y;
g2d.setColor(Color.BLACK);
g2d.drawString(lifePointString, a, b);
}
private Color calculateBarColor(int lifePoints) {
int red = 0;
int green = 204;
int blue = 0;
if (lifePoints <= 100) {
red = 204;
if (lifePoints <= 40) {
green = 0;
}
}
return new Color(red, green, blue);
}
private Font getHeadlineFont() {
return new Font("Comic Sans MS", Font.BOLD, 16);
}
}
public class MathFighterModel {
private int answer, enemyLifePoints, playerLifePoints;
public MathFighterModel() {
this.enemyLifePoints = 200;
this.playerLifePoints = 200;
}
public String generateRandomMathQuestion() {
String questionString = "";
int questionType = (int) (Math.random() * 4) + 1;
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
int number3 = (int) (Math.random() * 10) + 10;
if (playerLifePoints > 100) {
if (questionType == 1) {
this.answer = number1 + number2;
questionString = "What is " + number1 + " + " + number2
+ " ?";
} else if (questionType == 2) {
this.answer = number1 - number2;
questionString = "What is " + number1 + " - " + number2
+ " ?";
} else if (questionType == 3) {
this.answer = number1 * number2;
questionString = "What is " + number1 + " X " + number2
+ " ?";
} else if (questionType == 4) {
this.answer = number1 * number2 / number3;
questionString = "What is " + number1 + " X " + number2
+ " / " + number3 + " ?";
}
} else {
if (questionType == 1) {
this.answer = number1 * number2 + number3;
questionString = "What is " + number1 + " X " + number2
+ " + " + number3 + " ?";
} else if (questionType == 2) {
this.answer = number1 * number2 - number3;
questionString = "What is " + number1 + " X " + number2
+ " + " + number3 + " ?";
} else if (questionType == 3) {
this.answer = (number1 * number2) / (number2 + number3);
questionString = "What is (" + number1 + " x " + number2
+ ") / (" + number2 + " + " + number3 + ") ?";
} else if (questionType == 4) {
this.answer = (number1 * number2) / (number2 - number3);
questionString = "What is (" + number1 + " x " + number2
+ ") / (" + number2 + " - " + number3 + ") ?";
}
}
return questionString;
}
public void incrementPlayerLife(int increment) {
this.playerLifePoints += increment;
this.enemyLifePoints -= increment;
}
public boolean isAnswerCorrect(int userAnswer) {
return userAnswer == answer;
}
public int getEnemyLifePoints() {
return enemyLifePoints;
}
public int getPlayerLifePoints() {
return playerLifePoints;
}
}
}

logic error? diving 2 int that result in a float

I am writing a combat simulator. My attacker class initiates an attack and my defender class is supposed to block it. manager is my main class that computes and prints the results. My problem is with my highRatio, mediumRatio and lowRatio variables. If they are not equal to 1 all of them are set to zero. Any ideas as to what may be going?
//defender class
public int defenseSelector(int highAtkCounter, int mediumAtkCounter, int lowAtkCounter, int rounds, int roundCounter)
{
Random defenseTypeGenerator;
int defense = 0;
float highRatio;
float mediumRatio;
float lowRatio;
defenseTypeGenerator = new Random();
int defenseType = defenseTypeGenerator.nextInt(MAX_ROUNDS) + 1;
highRatio = highAtkCounter/roundCounter;
mediumRatio = mediumAtkCounter/roundCounter;
lowRatio = lowAtkCounter/roundCounter;
if(roundCounter > 3 && roundCounter <= rounds) //AI portion
{
if (highRatio > mediumRatio && highRatio > lowRatio)
{
defense = HIGH;
}
else if (mediumRatio > highRatio && mediumRatio > lowRatio)
{
defense = MEDIUM;
}
else if (lowRatio > highRatio && lowRatio > mediumRatio)
{
defense = LOW;
}
else
{
System.out.println("AI ERROR ratios " + highRatio + " " + mediumRatio + " " + lowRatio);
System.out.println("AI ERROR atkCounters " + highAtkCounter + " " + mediumAtkCounter + " " + lowAtkCounter);
System.out.println("AI ERROR rCounters " + roundCounter);
//manager class
while(roundCounter <= rounds)
{
int attack = theAttacker.attackSelector(high, medium, low);
int highAtkTracker = theAttacker.countHighAtks(attack);
System.out.println("DEBUG " + attack);
System.out.println("DEBUG " + highAtkTracker);
int mediumAtkTracker = theAttacker.countMediumAtks(attack);
System.out.println("DEBUG " + attack);
System.out.println("DEBUG " + mediumAtkTracker);
int lowAtkTracker = theAttacker.countLowAtks(attack);
System.out.println("DEBUG " + attack);
System.out.println("DEBUG " + lowAtkTracker);
highAtkCounter = highAtkCounter + highAtkTracker;
mediumAtkCounter = mediumAtkCounter + mediumAtkTracker;
lowAtkCounter = lowAtkCounter + lowAtkTracker;
int defense = theDefender.defenseSelector(highAtkCounter, mediumAtkCounter, lowAtkCounter, rounds, roundCounter);
In java any arithmetic operation with an integer results in an integer.
Therefore you must cast the integer into the floating point type explicitly:
highAtkCounter = highAtkCounter + (float)highAtkTracker;
mediumAtkCounter = mediumAtkCounter + (float)mediumAtkTracker;
lowAtkCounter = lowAtkCounter + (float)lowAtkTracker;

Return value does not change - java

My parameter value doesn't seem to change after I pass it through, edit it and return it - It remains the same.
Can I have some help on where I am doing wrongly? I'm creating a simple gun class program. The problem occurs in my reload method. When I reload the bullets to the gun, the bulletsRemaining in the gun becomes the maximum capacity, but the ammo value doesn't decrease.
public class Gun {
String name;
String sound;
int minDamage;
int maxDamage;
int shotsPerSecond;
int capacity;
int bulletsRemaining;
public Gun(String name, String sound, int minDamage, int maxDamage, int shotsPerSecond, int capacity, int bulletsRemaining) {
this.name = name;
this.sound = sound;
this.minDamage = minDamage;
this.maxDamage = maxDamage;
this.shotsPerSecond = shotsPerSecond;
this.capacity = capacity;
this.bulletsRemaining = bulletsRemaining;
}
public void fire() {
Random rnd = new Random();
int totalDamage = 0;
for(int x = 0; x<shotsPerSecond; x++)
{
int damage = rnd.nextInt(maxDamage) + 1;
System.out.print(sound + "(" + damage + ")");
totalDamage += damage;
}
System.out.println(" --> " + totalDamage + " Dmg/Sec ");
}
public void fireAtWill() {
Random rnd = new Random();
int totalDamage = 0;
while(bulletsRemaining > 0) {
for(int x = 0; x<shotsPerSecond; x++)
{
int damage = rnd.nextInt(maxDamage) + 1;
System.out.print(sound + "(" + damage + ")");
totalDamage += damage;
bulletsRemaining--;
if(bulletsRemaining == 0)
break;
}
System.out.println(" --> " + totalDamage + " Dmg/Sec ");
totalDamage = 0;
}
}
public int reload(int ammo) {
//System.out.println();
//System.out.println("Bullets remaining: " + bulletsRemaining);
//System.out.println("Ammo remaining: " + ammo);
//System.out.println("Reloading " + name);
int bulletsReload = capacity - bulletsRemaining; //Amount of bullets to be loaded to gun
ammo = ammo -= bulletsReload;
bulletsRemaining = bulletsRemaining += bulletsReload; //Fill bulletsRemaining to the max again after reloading
return ammo;
}
public void supressiveFire(int ammo) {
Random rnd = new Random();
int totalDamage = 0;
while(ammo != 0) {
while(bulletsRemaining > 0) {
for(int x = 0; x<shotsPerSecond; x++)
{
int damage = rnd.nextInt(maxDamage) + 1;
System.out.print(sound + "(" + damage + ")");
totalDamage += damage;
bulletsRemaining--;
}
System.out.println(" --> " + totalDamage + " Dmg/Sec ");
totalDamage = 0;
if(bulletsRemaining == 0)
reload(ammo);
}
}
if(ammo == 0)
System.out.println("Out of ammunition)");
}
public static void main(String[] args) {
// TODO code application logic here
int ammo = 5;
Gun g1 = new Gun("MK16", "Bang!", 10,15,5,5,5);
g1.fire();
g1.reload(ammo);
System.out.println("Ammo left: " + ammo);
System.out.println("Bullets left: " + g1.bulletsRemaining);
}
}
Expected output:
Ammo: 0
Bullets Remaining: 5
Output I received:
Ammo: 5
Bullets Remaining: 5
You should assign it back like below.
ammo = g1.reload(ammo);
in the main
public static void main(String[] args) {
// TODO code application logic here
int ammo = 5;
Gun g1 = new Gun("MK16", "Bang!", 10,15,5,5,5);
g1.fire();
ammo = g1.reload(ammo);
System.out.println("Ammo left: " + ammo);
System.out.println("Bullets left: " + g1.bulletsRemaining);
}

Yahtzee - Java - Error

I am trying to do a Yahtzee program. I start with trying to get the card pairs to work out before I continue with rest.
public class PlayEngine {
public PlayEngine(){}
public int evaluate(int[] dicePoints){
double dice1 = Math.random()*6+1;
int diceint1 = (int) dice1;
double dice2 = Math.random()*6+1;
int diceint2 = (int) dice2;
double dice3 = Math.random()*6+1;
int diceint3 = (int) dice3;
double dice4 = Math.random()*6+1;
int diceint4 = (int) dice4;
double dice5 = Math.random()*6+1;
int diceint5 = (int) dice5;
/* int[] dicePoints = {dice1, dice2, dice3, dice4, dice5}; */
int par = 0;
if(dice1==dice2 || dice1==dice3 || dice1==dice4 || dice1==dice5 || dice2==dice3 || dice2==dice4 || dice2==dice5 || dice3==dice4 || dice3==dice5 || dice4==dice5)
{
par = 1;
return par;
} else {
return par;
}
} //dicePoints
} //PlayEngine
When I run this, I get no errors. I only get up the "No main methods..", and that is how it should be.
When I try to run the program we got from school to test if the score:
import javax.swing.*;
import java.util.*;
public class TestScore {
public static void main(String[] args) {
int[] dicePoints = new int[5];
int[] playPoints = new int[15];
PlayEngine player = new PlayEngine ();
String[] kategori = {"Ettor ",
"Tvåor ",
"Treor ",
"Fyror ",
"Femmor ",
"Sexor ",
"Par ",
"Två Par ",
"Triss ",
"Fyrtal ",
"Liten stege ",
"Stor stege ",
"Kåk ",
"Chans ",
"Yatzy "};
String indata, utdata;
while(true) {
indata = JOptionPane.showInputDialog("Ange tärningarnas värden: ");
if (indata == null) // Avsluta genom att trycka Cancel
break;
StringTokenizer ordSeparator = new StringTokenizer(indata, " ,\t");
if (ordSeparator.countTokens() == 5) {
int index = 0;
while(ordSeparator.hasMoreTokens() && index < 5) {
String ettOrd = ordSeparator.nextToken();
dicePoints[index] = Integer.parseInt(ettOrd);;
index = index + 1;
}
playPoints = player.evaluate(dicePoints);
utdata = "Tärningarnas värden: ";
for (int i = 0; i < dicePoints.length; i = i + 1)
utdata = utdata + dicePoints[i] + " ";
utdata = utdata + "\n";
for (int i = 0; i <playPoints.length; i = i + 1) {
utdata = utdata + kategori[i] + playPoints[i] + "\n";
}
JOptionPane.showMessageDialog(null, utdata);
}
else
JOptionPane.showMessageDialog(null, "Du har angivt felaktigt antal värden!!!");
}
}//main
} //TestScore
I get this error:
TestScore.java:36: error: incompatible types: int cannot be converted to int[]
playPoints = player.evaluate(dicePoints);
^
How come? What is wrong?
Updated code:
import javax.swing.*;
import java.util.*;
public class TestScore {
public static void main(String[] args) {
int[] dicePoints = new int[5];
int playPoints;
PlayEngine player = new PlayEngine ();
String[] kategori = {"Ettor ",
"Tvåor ",
"Treor ",
"Fyror ",
"Femmor ",
"Sexor ",
"Par ",
"Två Par ",
"Triss ",
"Fyrtal ",
"Liten stege ",
"Stor stege ",
"Kåk ",
"Chans ",
"Yatzy "};
String indata, utdata;
while(true) {
indata = JOptionPane.showInputDialog("Ange tärningarnas värden: ");
if (indata == null) // Avsluta genom att trycka Cancel
break;
StringTokenizer ordSeparator = new StringTokenizer(indata, " ,\t");
if (ordSeparator.countTokens() == 5) {
int index = 0;
while(ordSeparator.hasMoreTokens() && index < 5) {
String ettOrd = ordSeparator.nextToken();
dicePoints[index] = Integer.parseInt(ettOrd);;
index = index + 1;
}
playPoints = player.evaluate(dicePoints);
utdata = "Tärningarnas värden: ";
for (int i = 0; i < dicePoints.length; i = i + 1)
utdata = utdata + dicePoints[i] + " ";
utdata = utdata + "\n";
for (int i = 0; i <playPoints.length; i = i + 1) {
utdata = utdata + kategori[i] + player.evaluate(dicePoints) + "\n";
}
JOptionPane.showMessageDialog(null, utdata);
}
else
JOptionPane.showMessageDialog(null, "Du har angivt felaktigt antal värden!!!");
}
}//main
} //TestScore
evaluate method return int (defined as public int evaluate(int[] dicePoints){) and not int[]. You are trying to save value returned from evaluate method as an array here:
playPoints = player.evaluate(dicePoints);
as you defined playPoints variable as int[] playPoints = new int[15];
Change it to int playPoints;

Longest monotonic subsequence algorithm NOT longest increasing algorithm

I have some numbers at the input:
1 1 7 3 2 0 0 4 5 5 6 2 1
And I look for a longest monotonic subsequence and what is the sum of this subsequence. The result is:
6 20
I cannot find the algorithm at the internet. Do you own/found one? This is about longest monotonic not longest increasing subsequence.
Definition of monotonic: http://en.wikipedia.org/wiki/Monotonic_function
I know that someone will ask: What have you tried? So i tried writing it(please don't check it I only post it so no one asks that question above I look for different algorithm->optimal one)
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Rozwiazanie {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//2^63 > 10^16 = 10^7 * 10^9 longi starcza
//10^9 inty starcza
//int 32 bity, long 64 bity
long podsuma = 0;
int dlugosc = 0;
int maxDlugosc = 0;
long maxPodsuma = 0;
int poczatekRownych = 0;
int poprzedniWyraz = 0, aktualnyWyraz;//uwaga jakby cos nie gralo w sprawdzarce zmien typ na long
boolean czyRosnacy = false, rowny = false;
String[] splittedLinia = br.readLine().split((char) 32 + "");//moglaby byc " " ale tak na wszelki wypadek nie ma chuja zeby sie popierdolilo teraz nawet na linuxie
for (int i = 0; i < splittedLinia.length; i++) {
if (i == 0) {
aktualnyWyraz = Integer.parseInt(splittedLinia[0]);
maxDlugosc = dlugosc = 1;
maxPodsuma = podsuma = aktualnyWyraz;
if (splittedLinia.length > 1) {
int nastepnyWyraz = Integer.parseInt(splittedLinia[1]);
czyRosnacy = nastepnyWyraz > aktualnyWyraz;
rowny = nastepnyWyraz == aktualnyWyraz;
}
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 1);
} else {
aktualnyWyraz = Integer.parseInt(splittedLinia[i]);
System.out.println(rowny);
if (aktualnyWyraz == poprzedniWyraz && rowny) {
podsuma += aktualnyWyraz;
dlugosc++;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 2);
} else if (rowny) {
rowny = false;
czyRosnacy = aktualnyWyraz > poprzedniWyraz;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 3);
}
if (!rowny) {
if (aktualnyWyraz >= poprzedniWyraz && czyRosnacy) {
podsuma += aktualnyWyraz;
dlugosc++;
System.out.println("akt:" + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 4);
} else if (aktualnyWyraz <= poprzedniWyraz && !czyRosnacy) {
podsuma += aktualnyWyraz;
dlugosc++;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 5);
} else {
// if (aktualnyWyraz == poprzedniWyraz) {
rowny = true;
// } else {
if (maxDlugosc < dlugosc) {
maxDlugosc = dlugosc;
maxPodsuma = podsuma;
}
podsuma = poprzedniWyraz + aktualnyWyraz;
dlugosc = 2;
czyRosnacy = aktualnyWyraz > poprzedniWyraz;
rowny = aktualnyWyraz == poprzedniWyraz;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 6);
//}
}
}
}
poprzedniWyraz = aktualnyWyraz;
}
System.out.println(maxDlugosc + " " + maxPodsuma);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//65 87 47 5 12 74 25 32 78 44 40 77 85 4 29 57:
try this one:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Rozwiazanie {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] splittedLinia = br.readLine().split((char) 32 + "");//moglaby byc " " ale tak na wszelki wypadek nie ma chuja zeby sie popierdolilo teraz nawet na linuxie
int aktualnyWyraz = Integer.parseInt(splittedLinia[0]);//uwaga jakby cos nie gralo w sprawdzarce zmien typ na long
int poprzedniWyraz = 0;
long podsumaRosnaca = aktualnyWyraz;
long podsumaSpadajaca = aktualnyWyraz;
int dlugoscRosnaca = 1;
int dlugoscSpadajaca = 1;
int maxDlugosc = 1;
long maxPodsuma = aktualnyWyraz;
int czyRosnacy = 0; // 0 -- nie znane (jezeli w poczatku wszystkie liczby sa rowne), 1 -- rosnacy, -1 -- spadajacy
boolean rowny = false;
System.out.println("akt: " + aktualnyWyraz + " dlR: " + dlugoscRosnaca + " podsumaR: " + podsumaRosnaca + " dlP: " + dlugoscSpadajaca + " podsumaP: " + podsumaSpadajaca);
for (int i = 1; i < splittedLinia.length; i++) {
poprzedniWyraz = aktualnyWyraz;
aktualnyWyraz = Integer.parseInt(splittedLinia[i]);
if (aktualnyWyraz == poprzedniWyraz) {
podsumaRosnaca += aktualnyWyraz;
podsumaSpadajaca += aktualnyWyraz;
dlugoscRosnaca++;
dlugoscSpadajaca++;
rowny = true;
} else { // rozne liczby
if (aktualnyWyraz > poprzedniWyraz) { // rosnie
podsumaRosnaca += aktualnyWyraz;
dlugoscRosnaca++;
if (rowny) {
dlugoscSpadajaca = 1;
podsumaSpadajaca = 0;
rowny = false;
}
if (czyRosnacy < 0) {
if (dlugoscSpadajaca > maxDlugosc) {
maxDlugosc = dlugoscSpadajaca;
maxPodsuma = podsumaSpadajaca;
}
podsumaSpadajaca = 0;
dlugoscSpadajaca = 1;
}
czyRosnacy = 1;
} else { // spada
podsumaSpadajaca += aktualnyWyraz;
dlugoscSpadajaca++;
if (rowny) {
dlugoscRosnaca = 1;
podsumaRosnaca = 0;
rowny = false;
}
if (czyRosnacy == 1) {
if (dlugoscRosnaca > maxDlugosc) {
maxDlugosc = dlugoscRosnaca;
maxPodsuma = podsumaRosnaca;
}
podsumaRosnaca = 0;
dlugoscRosnaca = 1;
}
czyRosnacy = -1;
}
}
System.out.println("akt: " + aktualnyWyraz + " dlR: " + dlugoscRosnaca + " podsumaR: " + podsumaRosnaca + " dlP: " + dlugoscSpadajaca + " podsumaP: " + podsumaSpadajaca);
}
System.out.println("maxDlugosc " + maxDlugosc + " maxPodsuma " + maxPodsuma);
} catch (Exception e) {
e.printStackTrace();
}
}
}
what I had to change:
you need a counter [dlugosc] (+ sum [podsuma]) for ascending
[rosnacy] and descending [spadajacy] values, as you need to count
both when the values are the same [rowny].
I changed boolean "rowny"
[equal] to int, as I thought that there are 3 values possible:
ascending, descending or unknown. If there are several equal values
at the beginning, there's all the time "unknown".
this program needs at least one number, but therefore you don't need to check in every
iteration of the loop whether i == 0 or not.
Going through the
numbers, I have to check several things, most important is, whether
the actual value [aktualnyWyraz] and the last used value
[poprzedniWyraz] are the same (then all counters and sums have to be
changed) or different. Different can mean ascending or descending, so
we have to increment the related counters and sum up the related sum.
What happens the "opposite" variables? Well, we need to check whether
the counter is bigger then the maximum one (so maybe these values are
useful for the result) and then set them back to their start.

Categories

Resources