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;
Related
public static void stats(){
System.out.println("\nName : " +characterName+ " " +characterClass);
System.out.println("Level : " + Level); //Output the value of Level
do {
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[]{"Str", "Dex", "Con", "Int", "Wis", "Cha"};
int amount;
for (int i = 0; i<statValues.length;i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i]+ " : " +statValues[i]);
if (amount == 10 || amount == 11) {
Bonus = 0;
System.out.print(" [ " + Bonus + "]\n");
}
//Bonus value for integers less than 10
else if (amount < 10) {
Bonus = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus + "]\n");
}
//Bonus value for integers greater than 10
else {
Bonus = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
}
while (reRoll.equals("yes"));
}
}
This is just a part of a code. Here i need to calculate the bonus for the Con stat using the variable conBonus. Because in the main method i need to calculate the hitpoints and for that the bonus value used is the bonus in conBonus.
Below is the class where the main method is given.
public class Game {
public static void main(String[] args) {
Character.level();
Character.Class();
Character.stats();
int hitPoints;
hitPoints = Character.Level*((int)((Math.random()*Character.hitDice)+1)+Character.conBonus);
System.out.println("HP : [" +hitPoints+ "]");
}
Will passing the bonus amounts to an array work. If so how can i pass it?
Here is how to store Bonus for each category:
First, change Bonus from an int to an array:
static int[] Bonus;
And in main, create a size of 6:
Bonus = new int[6];
Now to calculate hitPoints, use the array (notice that "Con" is array value 2, or the third element of the array: { "Str", "Dex", "Con", "Int", "Wis", "Cha" }
hitPoints = Character.Level * ((int) ((Math.random() * Character.hitDice) + 1) + Character.Bonus[2]);
Here is the new stats method, which uses the new Bonus array:
public static void stats() {
do {
System.out.println("\nName : " + characterName + " " + characterClass);
System.out.println("Level : " + Level); // Output the value of Level
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[] { "Str", "Dex", "Con", "Int", "Wis", "Cha" };
int amount;
for (int i = 0; i < statValues.length; i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i] + " : " + statValues[i]);
if (amount == 10 || amount == 11) {
Bonus[i] = 0;
System.out.print(" [ " + Bonus[i] + "]\n");
}
// Bonus value for integers less than 10
else if (amount < 10) {
Bonus[i] = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus[i] + "]\n");
}
// Bonus value for integers greater than 10
else {
Bonus[i] = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus[i] + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
} while (reRoll.equals("yes"));
}
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);
}
I'm a college student and this code is for a project in my intro to Java course. I've worked with it over and over again, searched for answers both on stackoverflow and others websites, but I still can't figure out what the problem is. The program is meant to store Clients by prompting for a First and Last name, and a email address. The client will be given a Client ID, and they can use that to either book a storage unit, or display a booked storage unit. When I run the program I get this exception:
Exception in thread "main" java.lang.NullPointerException
at Webstore3.WebStorage.Sub_Menu(WebStorage.java:153)
at Webstore3.WebStorage.main(WebStorage.java:85)
I've seen the questions and answers on stackoverflow regarding NullPointerExceptions, and I've done test code to make sure there is something in both input and customer[i].Client_ID, but I've yet to realize what the problem is. I know that the code isn't perfect, but any and all help in getting past this first error would be greatly appreciated.
package Webstore3;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
import java.lang.StringBuilder;
public class WebStorage
{
static int c = 0;
static int b = 0;
static int s = 0;
static WebStorage temp_w = new WebStorage();
static Customer temp_c;
static Booking temp_b;
static Storage temp_s;
static int i = 0;
static int j = 0;
static int k = 0;
static int Confirm;
static int Choose;
static String input = new String("");
static int temp = 0;
static String temp_string = "";
static String temp_string2 = "";
static Random r = new Random();
static Customer[] customer = new Customer[100];
static Booking[] booking = new Booking[14];
static Storage[] storage = new Storage[14];
//static ArrayList<Customer> customer2 = new ArrayList<Customer>();
//static ArrayList<Customer> booking2 = new ArrayList<Customer>();
//static ArrayList<Customer> storage2 = new ArrayList<Customer>();
static int w = 0;
static int l = 0;
public static void main(String[] args)
{
Confirm = JOptionPane.showConfirmDialog(null, "Would you like to Access ~WebStorage~?");
if(Confirm == 0)
{
while(temp != 3)
{
temp = MainMenu();
if(temp == 1)
{
temp_c = new Customer();
temp_c.First_Name();
temp_c.Last_Name();
temp_c.Email();
temp_string = temp_c.Account_Created();
customer[c] = temp_c;
if(Confirm == 0 )
{
c++;
input = JOptionPane.showInputDialog("What would you like to do now?" + "\n" + "\n" + "Book Unit - (1)" + "\n" + "Main Menu - (2)");
Choose = Integer.parseInt(input);
if(Choose == 1)
{
input = JOptionPane.showInputDialog("Enter unit width: ");
w = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Enter unit length: ");
l = Integer.parseInt(input);
temp_s = new Storage();
temp_string2 = temp_s.Storage(w, l);
storage[s] = temp_s;
if(temp_string2 != "")
{
temp_b = new Booking();
temp_b.Storage_ID = temp_string2;
temp_b.Client_ID = temp_string;
booking[b] = temp_b;
b++;
}
}
}
}
if(temp == 2)
{
Sub_Menu();
}
if(temp == 3)
{
JOptionPane.showMessageDialog(null, "Goodbye");
System.exit(0);
}
}
}
if(Confirm == 1)
{
System.out.println("Goodbye");
System.exit(0);
}
}
public static int MainMenu()
{
input = JOptionPane.showInputDialog("Please enter the number correspoding to your desired action: " + "\n" + "\n" + "Create an Account - (1)" + "\n" + "Booking - (2)" + "\n" + "Quit Program - (3)" +"\n");
temp = Integer.parseInt(input);
return temp;
}
public static void Sub_Menu()
{
input = JOptionPane.showInputDialog("Please enter the number correspoding to your desired action: " + "\n" + "\n" + "Book Storage - (1)" + "\n" + "Search Booking - (2)" + "\n" + "Display all Booking - (3)" +"\n" + "Main Menu - (4)");
Choose = Integer.parseInt(input);
if(Choose == 1)
{
input = JOptionPane.showInputDialog("Enter your Client ID: ");
temp_string = input;
for(i = 0; i < customer.length; i++)
{
if(input == customer[i].Client_ID)
{
input = JOptionPane.showInputDialog("Enter unit width: ");
w = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Enter unit length: ");
l = Integer.parseInt(input);
temp_s = new Storage();
temp_string2 = temp_s.Storage(w, l);
storage[s] = temp_s;
if(temp_string2 != "")
{
temp_b = new Booking();
temp_b.Storage_ID = temp_string2;
temp_b.Client_ID = temp_string;
booking[b] = temp_b;
b++;
}
}
}
JOptionPane.showMessageDialog(null, "Client ID not found!" + "\n" + "\n" + "Press ok, to return to the main menu and create an account");
}
if(Choose == 2)
{
input = JOptionPane.showInputDialog("Enter your Client ID: ");
for(i = 0; i < customer.length; i++)
{
if(input == customer[i].Client_ID)
{
input = JOptionPane.showInputDialog("Enter your Storage ID: ");
for(i = 0; i < storage.length; i++)
{
if(input == storage[i].Storage_ID)
{
JOptionPane.showMessageDialog(null, "size: " + storage[i].sb2 + "\n" + "Rental: " + storage[i].price_h + "\n" + "Storage ID: " + storage[i].sb + "\n" + "\n" + "Press ok, to return to the Main menu");
}
}
}
}
}
if(Choose == 3)
{
input = JOptionPane.showInputDialog("Enter you Client ID: ");
for(i = 0; i < customer.length; i++)
{
if(input == customer[i].Client_ID)
{
for(j = 0; j < booking.length; j++)
{
if(input == booking[j].Client_ID)
{
for(k = 0; k < storage.length; k++)
{
if(booking[j].Storage_ID == storage[k].Storage_ID)
{
JOptionPane.showMessageDialog(null, "First Name: " + customer[i].Client_FirstName + "\n" + "Last Name: " + customer[i].Client_LastName + "\n"+ "Email: " + customer[i].Client_Email + "\n" + "size: " + storage[k].sb2 + "\n" + "Rental: " + storage[k].price_h + "\n" + "Storage ID: " + storage[k].sb + "\n" + "\n");
}
}
}
}
}
}
}
if(Choose == 4)
{
}
}
}
class Customer extends WebStorage
{
static String input = new String("");
static boolean error;
static int Confirm = 0;
static int Valid_Email = 0;
static int Valid_ID = 0;
String Client_FirstName = "";
String Client_LastName = "";
String Client_Number = "";
String Client_Email = "";
static int[] temp_array = new int[9];
static int[] Client_ID_Array = new int[9];
String Client_ID = "";
StringBuilder sb;
Customer()
{
Client_FirstName = new String("");
Client_LastName = new String("");
Client_Number = new String("");
Client_Email = new String("");
Client_ID = new String("");
sb = new StringBuilder("");
}
Customer(String Client_FirstName, String Client_LastName, String Client_Number, String Client_Email, String Client_ID, StringBuilder sb)
{
this.Client_FirstName = Client_FirstName;
this.Client_LastName = Client_LastName;
this.Client_Number = Client_Number;
this.Client_Email = Client_Email;
this.Client_ID = Client_ID;
this.sb = sb;
}
public void First_Name()
{
input = JOptionPane.showInputDialog("Enter your Information to create an account: " + "\n" + "\n" + "First Name: ");
for(int i = 0; i < input.length(); i++)
{
error = Character.isLetter(input.charAt(i));
if(error == false)
{
input = JOptionPane.showInputDialog("Your name may only contain letters" + "\n" + "\n" + "First Name: ");
error = Character.isLetter(input.charAt(i));
i = -1;
}
}
Client_FirstName = input;
}
public void Last_Name ()
{
input = JOptionPane.showInputDialog("Enter your Information to create an account: " + "\n" + "\n" + "Last Name: ");
for(int i = 0; i < input.length(); i++)
{
error = Character.isLetter(input.charAt(i));
if(error == false)
{
input = JOptionPane.showInputDialog("Your name may only contain letters" + "\n" + "\n" + "Last Name: ");
error = Character.isLetter(input.charAt(i));
i = -1;
}
}
Client_LastName = input;
}
public void Email ()
{
input = JOptionPane.showInputDialog("Enter your Information to create an account: " + "\n" + "\n" + "Email: (Must contain a #, and end with .com, .net, .org, or .edu) ");
while(Valid_Email < 2)
{
Valid_Email = 0;
error = input.contains("#");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".com");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".net");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".org");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".edu");
if(error == true)
{
Valid_Email++;
}
if(Valid_Email < 2)
{
input = JOptionPane.showInputDialog("Invalid email entered! " + "\n" + "\n" + "Email: (Must contain a #, and end with .com, .net, .org, or .edu) ");
}
}
Client_Email = input;
}
public String Account_Created()
{
Confirm = JOptionPane.showConfirmDialog(null, "Account Created!" + "\n" + "Is everything correct?" + "\n" + "First Name: " + Client_FirstName + "\n" + "Last Name: " + Client_LastName + "\n"+ "Email: " + Client_Email);
if(Confirm == 0)
{
do{
for(i = 0; i < temp_array.length; i++)
{
temp_array[i] = r.nextInt(9);
}
for(i = 0; i < customer.length; i++)
{
for(int j = 0; j < Client_ID_Array.length; j++)
{
if(temp_array[j] == customer[i].Client_ID_Array[j])
{
Valid_ID++;
}
}
}
}while(Valid_ID == 9);
Client_ID_Array = temp_array;
for(i = 0; i < Client_ID_Array.length; i++)
{
sb.append(Client_ID_Array[i]);
}
Client_ID = sb.toString();
JOptionPane.showMessageDialog(null, "Your Client ID#: " + Client_ID );
}
return Client_ID;
}
}
class Booking extends WebStorage
{
String Client_ID;
String Storage_ID;
static int i = 0;
String temp_string = "";
String input = "";
static int Choose = 0;
static int Choose2 = 0;
static int w = 0;
static int l = 0;
Booking()
{
Client_ID = "";
Storage_ID = "";
temp_string = "";
input = "";
}
Booking(String Client_ID, String Storage_ID, String temp_string, String input)
{
this.Client_ID = Client_ID;
this.Storage_ID = Storage_ID;
this.temp_string = temp_string;
this.input = input;
}
}
class Storage extends WebStorage
{
static int Confirm = 0;
static int[] width = { 5, 5, 10, 10, 10, 10, 10};
static int[] length = { 5, 10, 10, 15, 20, 25, 30};
static int[] unit = { 3, 3, 2, 2, 2, 1, 1};
static int[] price = {16, 33, 41, 73, 163, 245, 277};
static int price_h = 0;
static int total_units = 1;
String Storage_ID = "";
StringBuilder sb;
StringBuilder sb2;
static char by = 'x';
Storage()
{
Storage_ID = "";
sb = new StringBuilder();
sb2 = new StringBuilder();
}
Storage(String Storage_ID, StringBuilder sb, StringBuilder sb2)
{
this.Storage_ID = Storage_ID;
this.sb = sb;
this.sb2 = sb2;
}
public String Storage(int w, int l)
{
for(int i = 0; i < width.length; i++)
{
if(w == width[i] && l == length[i] && unit[i] > 0)
{
if(total_units < 10)
{
sb.append(0);
sb.append(total_units);
}
if(total_units > 9)
{
sb.append(total_units);
}
if(width[i] < 10)
{
sb.append(0);
sb.append(w);
if(length[i] < 10)
{
sb.append(0);
sb.append(l);
}
if(length[i] > 9)
{
sb.append(l);
}
}
if(width[i] > 9)
{
sb.append(w);
if(length[i] < 10)
{
sb.append(0);
sb.append(l);
}
if(length[i] > 9)
{
sb.append(l);
}
}
unit[i] = unit[i] - 1;
total_units = total_units + 1;
sb2.append(w);
sb2.append(by);
sb2.append(l);
price_h = price[i];
JOptionPane.showMessageDialog(null, "Storage Booked!" + "\n" + "\n" + "size: " + sb2 + "\n" + "Rental: " + price_h + "\n" + "Storage ID: " + sb );
Storage_ID = sb.toString();
WebStorage.s++;
}
if((w != width[i] && l !=length[i]) && unit[i] <= 0)
{
JOptionPane.showMessageDialog(null, "No storage units of that size are available");
}
if(total_units == 14)
{
JOptionPane.showMessageDialog(null, "All storage units are occupied!");
}
}
return Storage_ID;
}
Have a look at those points.
You declare an array of Customer with a size of 100.
static Customer[] customer = new Customer[100];
later in the code you loop over all array entries
for(i = 0; i < customer.length; i++)
But you do not check if at index i is already a reference to a Customer is stored. If not you get a NUllPointerException.
if(input == customer[i].Client_ID)
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);
}
}
}
}
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.