How to increment properly - java

i have an issue with my code where i can only increment the last input data value, this code it linked to another class where i have song list etc. however im tryin to create a playlist where when i press play it increments the playcount of all the songs in the playlist. however my problem is once i add the songs to a playlist, when i press play it only increments the last track in entered into the text field. for example i type "01" then add then i type "02" and add, but it only increments track 2 (hence the last track i added) instead of incrementing both 1 and 2. im very new to java so forgive me if this seems trivial, and thanks in advance.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == add) {
String key = trackNo.getText();
String name = LibraryData.getName(key);
if (name == null) {
playcount.setText("No such track number");
} else {
playcount.append("\n" + name + " - " + LibraryData.getArtist(key));
}
}
if (e.getSource() == reset) {
playcount.setText("");
}
if (e.getSource() == play) {
String key = trackNo.getText();
LibraryData.incrementPlayCount(key);
}
}
}

Related

Minecraft Spigot Remove item from inventory

I'm making a bedwars plugin in spigot 1.8_R3, I'm currently working on the shop system, when you click on an item to purchase it, 4 iron ingots should be removed from the players inventory.
inventory.remove(new ItemStack(getResource(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".type")), Integer.parseInt(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".cost"))));
However, this code only removes the iron if there are exactly 4 iron ingots. How would I make it so 4 iron ingots would be removed from different amounts such as 5?
Edit :
I tried to use this code :
public void removeItemFromInventory(Inventory inv, ItemStack currentItem, Player p) {
ItemStack item = new ItemStack(getResource(Main.plugin.getConfigValue("shop." + currentItem.getTypeId() + ".type")), Integer.parseInt(Main.plugin.getConfigValue("shop." + currentItem.getTypeId() + ".cost")));
if(inv.contains(item)) { // contains the exact item
inv.remove(item); // remove first time it find this item
} else { // doesn't contains this item
for(ItemStack invItem : inv.getContents()) {
if(invItem.getType().equals(item.getType())) { // if it's this type of item.
// You can add other check specially for ItemMeta ...
int amount = invItem.getAmount(); // amount of actual item
int stay = item.getAmount(); // keep amount
if(amount > stay) { // too many item, just change amount
invItem.setAmount(amount - stay); // change amount to remove it
break; // stop loop
} else if(amount < stay) { // not enough item
invItem.setAmount(0); // you can also remove the item by setting air to this slot
item.setAmount(stay - amount); // reduce amount of item to delete
}
}
}
}
FastShop shop = new FastShop(p );
p.closeInventory();
p.openInventory(shop.getInventory());
}
I'm currently getting a nullpointer error. I'm still need of help!
This part of code will search an item similar to "Iron Ingot x4". If it's not similar, it doesn't change what is it because it's just different.
You should do like that :
ItemStack item = new ItemStack(getResource(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".type")), Integer.parseInt(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".cost")));
if(inv.contains(item)) { // contains the exact item
inv.remove(item); // remove first time it find this item
} else { // doesn't contains this item
for(ItemStack invItem : inv.getContents()) {
if(invItem != null && invItem.getType().equals(item.getType()) { // if it's this type of item.
// You can add other check specially for ItemMeta ...
int amount = invItem.getAmount(); // amount of actual item
int stay = item.getAmount(); // keep amount
if(amount > stay) { // too many item, just change amount
invItem.setAmount(amount - stay); // change amount to remove it
break; // stop loop
} else if(amount < stay) { // not enough item
invItem.setAmount(0); // you can also remove the item by setting air to this slot
item.setAmount(stay - amount); // reduce amount of item to delete
}
}
}
}
player.updateInventory();
This isn't exactly a full solution with code. However, you can do this.
Create an integer for the amount of iron required.
Create a for loop that iterates through a players inventory and if that slot contains iron then:
if the amount in the slot is greater than the iron integer, remove the iron
integer from that slot and give the item that is owed. else remove the amount in the slot from the iron integer and delete that slot.
I hope you can solve your issue from this.

Make a method run in a method java for my game?

I'm struggling with dealing of inventory scan for my game, it basically search for the user inventory if "Flying Broom" if present(it was collected in another method and upload the code is too long), if not it will run the method challengedragon() again; else, it will proceed to the next challenge if the item is present.I was think of inserting method as parameter but it is not possible. This is what I have now. :
public class Main {
String Flyingbroom = "Flying broom";
public static void main(String[] args) {
Player_inventory p = new Player_inventory();
challengedragon();
}
public void challengedragon() {
System.out.println("a Hungarian Horntail dragon! Let's start the battle! You have four options to beat the dragon: ");
System.out.println("1: Fly away with your broom");
System.out.println("2: Fight the dragon");
System.out.println("3: Just run to the egg and get it");
System.out.println("4: Hide behind a rock");
System.out.println("5: Go back to Hogwart");
System.out.println("Your choice is: ");
Scanner in = new Scanner(System.in);
int dragonfightchoice = in .nextInt();
if (dragonfightchoice == 1) {
{
p.Scanitem(Flyingbroom,
"Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg",
"You dont have the broom. Try to search for the broom",
playerHP);
proceedtonextchallengelake();
} else if (dragonfightchoice == 2) {
System.out.println("The Hungarian Horntail dragon fired you. - 70HP. ");
playerHP -= 70;
challengedragon();
} else if (dragonfightchoice == 3) {
System.out.println("Bad idea... You lose 100 HP");
playerHP -= 100;
challengedragon();
} else if (dragonfightchoice == 4) {
System.out.println("The dragon found you. You lose 30 HP");
playerHP -= 30;
challengedragon();
} else if (dragonfightchoice == 5) {
Hogwart();
} else {
invalid();
challengedragon();
}
}
For my inventory class:
public void Scanitem(String item, String trueouputext, String textifconditionisnotmet) {
if (inv.contains(item) == true) {
System.out.println(trueouputext);
} else if (inv.contains(item) == false) {
System.out.println(textifconditionisnotmet);
}
public static ArrayList<String> inv = new ArrayList<String>();
Do you guys have any recommendation?
Are there additional steps to populate the inventory (variable inv)?
Also, wouldn't you want ScanItem to answer true or false, depending on whether the item was found? Then you would have something like this:
public boolean scanitem(String item) {
return ( inv.contains(item) );
}
if ( p.scanItem(flyingBroom) ) {
System.out.println("Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg");
} else {
System.out.println("You dont have the broom. Try to search for the broom");
}
That will get you closer to what you want. However, there are two other issues which you'll need to put into your code:
You will need a loop of some sort, instead of calling challengeDragon from inside of itself.
Somehow, the return value from scanItem must be used to decide whether to loop.
Currently, you do a nested call of a method each time the player does something, this means that sooner or later you'll run out of the stack. A better idea for the framework for your text-based adventure is to have some kind of a description of the current game's state. The state could be represented as an object that contains the following information:
where's the player currently at (on which step, at which "crossing" etc.)
the player's stats (HP, available skills etc.)
the contents of the player's inventory
some previously made choices affecting the game
Then, the code could be written as a simple loop that does the following:
process player's input
change the state according to the player's input
present the player with available options according to the new state
wait for the next input
repeat

Keymap Spacebar to Enter Key action in Java

I am trying to make it so that instead of hitting the enter key in my java program to make the enter action occur, I can instead hit the enter key while a custom method is running. At this point, I have looked into Hashmaps but am pretty confused if this going to do what I want. Any help would be greatly appreciated. It seems like this should be an easy thing to do, but for some reason I am just not getting a solution to it.
So, I am thinking my code will be something like this. Essentially, I am making a game of Hot Potato and I need to have the players take turn entering a character (e, d, and c for team 1 and o, k, and n for team 2). This will be involving a GUI interface as well. A have a while loop that will end once a timer reaches zero. What I would like is for the players to be able to put in a letter into a JTextField in the GUI and then simply press spacebar (as they will be sharing a keyboard). Once they enter the right letter (I made it randomized), they can hit spacebar and they will have "tossed the potato" to the other player.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
I am working all of this out of the actionPerformed(ActionEvent ev) method. The fuller code looks like this. The if statement is commented out because I would like the game to start when the main button is pressed, but right now I get a ton of compilation errors when I uncomment the JButton and have it working with the String text that is the dialogue from the text you enter into a JTextField.
public void actionPerformed(ActionEvent ev) {
Object eventSource = ev.getSource();
String text = entryText.getText(); // text entered into JText
//JButton eventButton = (JButton) eventSource;
System.out.println(text);
//if (eventButton.equals(main))
{
int totalTime = 1000*(HotPotato.randNum());
long startTime = System.currentTimeMillis();
System.out.println(totalTime/1000);
Boolean p1Start = false;
String input = "";
while (System.currentTimeMillis() - startTime <= totalTime)
{
p1Start = !p1Start;
char a = HotPotato.randLetterBoth(p1Start);
String aString = String.valueOf(a);
while (!input.equals(aString))
{
System.out.print(aString); // temporary, shows test letter
input = theKeyboard.next();
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
}
}
if (p1Start)
{
System.out.print("Team 2 Wins!");
}
else
{
System.out.print("Team 1 Wins!");
}
setLabels();
myPicture.makeHotPotatoOn(myHotPotato.state());
myPicture.repaint();
}
}

Java: Comparing [All] Instance Variables of an Object

I've a little problem.
Myself and a few friends were playing poker yesterday but we didn't have chips so I decided to start writing a program for that [Without Cards, just Chips].
In my code I have two main variables in the Game Object.
private int id;
private long bank;
I have a different file called Aside in which I can do different calculations.
In the code below I am trying to compare all instance bank variables to see if all the banks matched [In this case this will mean a new card can be drawn, otherwise users will have to keep to either raise or fold].
Is there a way of writing this in an easier term:
package poker;
import java.util.ArrayList;
public class Aside
{
public boolean compareBanks(ArrayList<Game> x)
{
ArrayList<Game> players = new ArrayList(x);
if(players.get(0).getBank() == players.get(1).getBank() && players.get(0).getBank() == players.get(2).getBank()
&& players.get(1).getBank() == players.get(2).getBank())
{
return true;
}
return false;
}
}
Later I use this here:
while(aside.compareBanks(players))
But the loop keeps going.
I'm fairly intermediate in programming so go easy on me with mistakes.
Thank you for your time.
P.S: This is NOT a code dump.
while(aside.compareBanks(players))
{
for(Game x : players)
{
if(x.hasPayedBid() == true)
{
System.out.println("Player : " + x.getName() + " [Call, Raise, Fold]:");
action = in.nextLine();
if(action.equalsIgnoreCase("call"))
{
break;
}else if(action.equalsIgnoreCase("raise"))
{
System.out.println("How much are you raising? $");
int raise = in.nextInt();
table += raise;
x.raise(raise);
}else
{
x.fold();
}
}
}
in.nextLine();
for(Game x : players)
{
System.out.println(x.toString() + "\n");
}
}//End While
You can do it using java-8 Stream API something like this
return players.stream().allMatch(p -> p.getBlank().equals( players.get(0).getBalnk()))
However if you will use while(aside.compareBanks(players)) and all elements of the list have equal blank value, your while loop will never stop. It is the same as while(true). So in this case you probably need to use if(aside.compareBanks(players)) or in case of equal blank values change them.
Try this
long bankValue=0;
For(Game player: players){
bankValue+=player.getBank();
}
if(bankValue==(players.get(0).getBank()*players.size)){
return true;}
else return false;

Error checking if statements

I am doing some practice work by expanding on a homework project I recently wrote. This is not for a grade, but I want to add some error checking to my code.
The program requires you to enter a name, select from a dropdown, select from a listbox and to select a radio button. My goal is to populate an error messagebox if any of the required items is blank.
The code I have so far for the error checking is below, but Im not sure how to take the individual lacking item and populate that to the message box since all of the error checking is in a single "if" statement.
Error checking code:
// Listener to handle the print button.
class ButtonListener implements ActionListener
{
ButtonListener() {}
public void actionPerformed(ActionEvent e)
{
JFrame frame1 = new JFrame("Show Message Dialog");
// Checks for required entries
if (error == 0 || name == "" || flag == 0)
{
JOptionPane.showMessageDialog(frame1,
"You must complete the form: " + missing, "ERROR",
JOptionPane.ERROR_MESSAGE);
}
else
{
// Get values from fields
setText();
System.out.println("Passenger's Name: " + name + "\n");
System.out.println("Age Group: " + ageValue + "\n");
for (int i = 0; i < value.length; i++)
{
System.out.println("Destination: " + value[i] + "\n");
}
System.out.println("Departure Day: " + day + "\n");
}
}
}
Thanks!
It looks like they can actually have multiple things wrong, so why only show one? I'm normally a C# dev so I'm not going to try to get the syntax right on typing this myself, but here's the concept:
Create a collection of some sort, like a list of strings.
Make 3 if statements, one for each of those errors, and put the field
names in for each one that fails. if (name.isEmpty()) {
errorList.Add("name"); }
Check to see if the count of items in the list is greater than 0. If
it is throw your error and put the name of the bad fields from the
collection into the string that you generate.

Categories