Importing Ticket class problem (java) - java

My program will not find the ticket class i created . Cant seem to work out what i have done wrong? Thank you
package javacw;
/*
*
* #Author Christopher Kempster;
*
*/
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame implements ActionListener {
public JButton buyButton, viewSeatsButton, clearSeatsButton;
String[] showTimes = {"1pm", "3pm", "5pm", "7pm", "9pm"};
String[] ageCategories = {"Adult", "Child", "OAP"};
String[] seatingSections = {"Left", "Middle", "Right"};
public JComboBox times, categories, sections;
public JTextField numberOfTickets;
public Ticket ticket;
public int price;
public static void main(String args[]) {
Main dashboard = new Main();
dashboard.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object item = times.getSelectedItem();
String stringTimes = (String)item;
Object item1 = categories.getSelectedItem();
String stringCategories = (String)item1;
Object item2 = sections.getSelectedItem();
String stringSections = (String)item2;
String text = numberOfTickets.getText();
int ii = Integer.parseInt(text);
if(e.getSource() == buyButton) {
buyTickets(stringTimes, stringSections, ii, stringCategories);
}
else if(e.getSource() == viewSeatsButton) {
showSeats(stringTimes, stringSections);
}
else if(e.getSource() == clearSeatsButton) {
clearSection(stringTimes, stringSections);
}
}
public Main() {
ticket = new Ticket();
JPanel panel = new JPanel();
FlowLayout flow = new FlowLayout();
panel.setLayout(flow);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 500);
buyButton = new JButton("Buy tickets");
viewSeatsButton = new JButton("View seats");
clearSeatsButton = new JButton("Clear seats");
times = new JComboBox(showTimes);
categories = new JComboBox(ageCategories);
sections = new JComboBox(seatingSections);
JLabel label = new JLabel("Number of tickets:");
numberOfTickets = new JTextField(5);
buyButton.addActionListener(this);
viewSeatsButton.addActionListener(this);
clearSeatsButton.addActionListener(this);
panel.add(times);
panel.add(categories);
panel.add(sections);
panel.add(label);
panel.add(numberOfTickets);
panel.add(buyButton);
panel.add(viewSeatsButton);
panel.add(clearSeatsButton);
Container cp = getContentPane();
cp.add(panel, BorderLayout.CENTER);
cp.setBackground(Color.red);
}
public void showSeats(String a, String b) {
JOptionPane.showMessageDialog(this, "There are " + ticket.seatsLeft(a, b) + " seats left in the " + b + " at " + a + ".");
}
public void clearSection(String a, String b) {
ticket.clearSeats(a, b);
JOptionPane.showMessageDialog(this, "There are now " + ticket.seatsLeft(a, b) + " tickets left for this section.");
}
public void buyTickets(String a, String b, int i, String c) {
if(c.equals("Adult")) {
price = 5;
}
else if(c.equals("Child")) {
price = 2;
}
else if(c.equals("OAP")) {
price = 2;
}
price = price * i;
if(ticket.buyTix(a, b, i)) {
JOptionPane.showMessageDialog(this, "Tickets have been bought!\nThere are " + ticket.seatsLeft(a, b) + " seats left in this section.\nPrice of tickets bought: £" + price + ".");
}
else {
JOptionPane.showMessageDialog(this, "Sorry, there are just " + ticket.seatsLeft(a, b) + " tickets left for this section.");
}
}
}
Ticket.java
package javacw;
/*
*
* #Author Christopher Kempster;
*
*/
public class Ticket {
int c, seatsLeft;
public int[] seating = {12, 40, 12, 12, 40, 12, 12, 40, 12, 12, 40, 12, 12, 40, 12};
public int[] seating2 = {12, 40, 12, 12, 40, 12, 12, 40, 12, 12, 40, 12, 12, 40, 12};
public Ticket() {
}
public void clearSeats(String a, String b) {
seating[convertArrayPointer(a, b)] = seating2[convertArrayPointer(a, b)];
}
public boolean buyTix(String a, String b, int i) {
if(seatsLeft(a, b) >= i) {
seating[convertArrayPointer(a, b)] -= i;
return true;
}
else {
return false;
}
}
public int seatsLeft(String a, String b) {
seatsLeft = seating[convertArrayPointer(a, b)];
return seatsLeft;
}
public int convertArrayPointer(String a, String b) {
if(a.equals("1pm") && b.equals("Left")) {
c = 0;
}
else if(a.equals("1pm") && b.equals("Middle")) {
c = 1;
}
else if(a.equals("1pm") && b.equals("Right")) {
c = 2;
}
else if(a.equals("3pm") && b.equals("Left")) {
c = 3;
}
else if(a.equals("3pm") && b.equals("Middle")) {
c = 4;
}
else if(a.equals("3pm") && b.equals("Right")) {
c = 5;
}
else if(a.equals("5pm") && b.equals("Left")) {
c = 6;
}
else if(a.equals("5pm") && b.equals("Middle")) {
c = 7;
}
else if(a.equals("5pm") && b.equals("Right")) {
c = 8;
}
else if(a.equals("7pm") && b.equals("Left")) {
c = 9;
}
else if(a.equals("7pm") && b.equals("Middle")) {
c = 10;
}
else if(a.equals("7pm") && b.equals("Right")) {
c = 11;
}
else if(a.equals("9pm") && b.equals("Left")) {
c = 12;
}
else if(a.equals("9pm") && b.equals("Middle")) {
c = 13;
}
else if(a.equals("9pm") && b.equals("Right")) {
c = 14;
}
return c;
}
}

This compiles properly when I try under Eclipse.
The problem doesn't come from your code. I think it comes from your environment settings. Either the source path is not correct or your Ticket.java is not located in the proper directory (which should be [src path]/javacw here).

Related

I created a game, but the counter for wins, losses and draws isn't working

One would think that this would be the easiest thing (it should be right), but my JLabel values are not being updated to reflect that the game is a draw, loss or win. I initiate 3 variables (numLosses, numDraws, and numWins), and then I increment them each time there is a loss, win or draw. However my counter remains at 0? Why? Here is the code?
NewTicTacToe.java:
package newtictactoe;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NewTicTacToe
extends JFrame
{
public static void main(String [] args)
{
new NewTicTacToe();
}
private JButton btnA1, btnA2, btnA3, btnB1, btnB2, btnB3, btnC1, btnC2, btnC3;
private JLabel lblWins, lblLosses, lblDraws;
private TicTacToeBoard board;
private int numWins, numDraws, numLosses;
public NewTicTacToe()
{
// Set up the grid
this.numDraws = 0;
this.numWins = 0;
this.numLosses = 0;
this.setSize(800,450);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Tic-Tac-Toe");
JPanel panel1 = new JPanel();
panel1.setSize(650,450); //resolution of panel1 set to 650 by 325
panel1.setLayout(new GridLayout(3,3));
btnA1 = createButton("A1");
btnA2 = createButton("A2");
btnA3 = createButton("A3");
btnB1 = createButton("B1");
btnB2 = createButton("B2");
btnB3 = createButton("B3");
btnC1 = createButton("C1");
btnC2 = createButton("C2");
btnC3 = createButton("C3");
panel1.add(btnA1);
panel1.add(btnA2);
panel1.add(btnA3);
panel1.add(btnB1);
panel1.add(btnB2);
panel1.add(btnB3);
panel1.add(btnC1);
panel1.add(btnC2);
panel1.add(btnC3);
JPanel panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
lblWins = new JLabel("Wins: " + numWins);
lblLosses = new JLabel("Losses: " + numLosses);
lblDraws = new JLabel("Draws: " + numDraws);
panel2.add(lblWins);
panel2.add(lblLosses);
panel2.add(lblDraws);
lblWins.setLocation(670, 20);
lblLosses.setLocation(670, 50);
lblDraws.setLocation(670, 80);
lblWins.setSize(100, 20);
lblLosses.setSize(100, 20);
lblDraws.setSize(100, 20);
panel2.setLayout(null);
this.add(panel1);
this.add(panel2);
this.setVisible(true);
// Start the game and create new instance of TicTacToeBoard
board = new TicTacToeBoard();
}
private JButton createButton(String square)
{
JButton btn = new JButton();
btn.setPreferredSize(new Dimension(50, 50));
Font f = new Font("Dialog", Font.PLAIN, 72);
btn.setFont(f);
btn.addActionListener(e -> btnClick(e, square));
return btn;
}
private void btnClick(ActionEvent e, String square)
{
if (board.getSquare(square) != 0)
return;
JButton btn = (JButton)e.getSource();
btn.setText("X");
board.playAt(square, 1);
if (board.isGameOver() == 3)
{
JOptionPane.showMessageDialog(null,
"It's a draw!", "Game Over",
JOptionPane.INFORMATION_MESSAGE);
numDraws++;
resetGame();
return;
}
if (board.isGameOver() == 1)
{
JOptionPane.showMessageDialog(null,
"You Win n00b!", "Game Over",
JOptionPane.INFORMATION_MESSAGE);
numWins++;
resetGame();
return;
}
String computerMove = board.getNextMove();
board.playAt(computerMove,2);
switch (computerMove)
{
case "A1":
btnA1.setText("O");
break;
case "A2":
btnA2.setText("O");
break;
case "A3":
btnA3.setText("O");
break;
case "B1":
btnB1.setText("O");
break;
case "B2":
btnB2.setText("O");
break;
case "B3":
btnB3.setText("O");
break;
case "C1":
btnC1.setText("O");
break;
case "C2":
btnC2.setText("O");
break;
case "C3":
btnC3.setText("O");
break;
}
if (board.isGameOver() == 2)
{
JOptionPane.showMessageDialog(null,
"Computer wins you big n00b!", "Game Over",
JOptionPane.INFORMATION_MESSAGE);
numLosses++;
resetGame();
return;
}
}
private void resetGame()
{
board.reset();
btnA1.setText("");
btnA2.setText("");
btnA3.setText("");
btnB1.setText("");
btnB2.setText("");
btnB3.setText("");
btnC1.setText("");
btnC2.setText("");
btnC3.setText("");
}
}
TicTacToeBoard.java:
package newtictactoe;
public class TicTacToeBoard
{
int numWins = 0;
int numLosses = 0;
int numDraws = 0;
private int board [];
private int vectors [] [] =
{
{0, 1, 2}, // Row 1
{3, 4, 5}, // Row 2
{6, 7, 8}, // Row 3
{0, 3, 6}, // Column 1
{1, 4, 7}, // Column 2
{2, 5, 8}, // Column 3
{0, 4, 8}, // Diagonal 1
{2, 4, 6} // Diagonal 2
};
public TicTacToeBoard()
{
this.reset();
}
public void reset()
{
board = new int[] {2, 2, 2, 2, 2, 2, 2, 2, 2};
}
private int getSquare(int index)
{
if (index < 0 | index > 8)
throw new IllegalArgumentException("index must be 0-9");
return board[index];
}
public int getSquare(String square)
{
int index = mapSquareToIndex(square);
if (index == -1)
throw new IllegalArgumentException("Invalid square");
switch (getSquare(index))
{
case 3:
return 1;
case 5:
return 2;
default:
return 0;
}
}
private int mapSquareToIndex(String square)
{
switch (square)
{
case "A1":
return 0;
case "A2":
return 1;
case "A3":
return 2;
case "B1":
return 3;
case "B2":
return 4;
case "B3":
return 5;
case "C1":
return 6;
case "C2":
return 7;
case "C3":
return 8;
default:
return -1;
}
}
private String mapIndexToSquare(int index)
{
switch (index)
{
case 0:
return "A1";
case 1:
return "A2";
case 2:
return "A3";
case 3:
return "B1";
case 4:
return "B2";
case 5:
return "B3";
case 6:
return "C1";
case 7:
return "C2";
case 8:
return "C3";
default:
return "";
}
}
public void playAt(String square, int player)
{
int index = mapSquareToIndex(square);
if (index == -1)
throw new IllegalArgumentException("Invalid square");
this.playAt(index, player);
}
private void playAt(int index, int player)
{
if (index < 0 | index > 8)
throw new IllegalArgumentException("Square must be 0-8");
if (player <1 | player > 2)
throw new IllegalArgumentException("Player must be 1 or 2");
if (board[index] != 2)
throw new IllegalArgumentException("Square is not empty.");
if (player == 1)
board[index] = 3;
else
board[index] = 5;
}
public int isGameOver()
{
// check for win
for (int v = 0; v < 8; v++)
{
int p = getVectorProduct(v);
if (p == 27) {
numWins++;
return 1;
} // Player 1 has won
if (p == 125) {
numLosses++;
return 2;
// Player 2 has won
}
}
// check for draw
int blankCount = 0;
for (int i = 0; i < 9; i++)
if (board[i] == 2)
blankCount++;
if (blankCount == 0) {
numDraws++;
return 3; // Game is a draw
}
return 0; // Game is not over
}
public String canPlayerWin(int player)
{
if (player <1 | player > 2)
throw new IllegalArgumentException("player must be 1 or 2");
boolean playerCanWin = false;
for (int v = 0; v < 8; v++)
{
int p = getVectorProduct(v);
if ( (player == 1 & p == 18)
| (player == 2 & p == 50) )
{
if (board[vectors[v][0]] == 2)
return mapIndexToSquare(vectors[v][0]);
if (board[vectors[v][1]] == 2)
return mapIndexToSquare(vectors[v][1]);
if (board[vectors[v][2]] == 2)
return mapIndexToSquare(vectors[v][2]);
}
}
return "";
}
private int getVectorProduct(int vector)
{
return board[vectors[vector][0]] *
board[vectors[vector][1]] *
board[vectors[vector][2]];
}
public String getNextMove()
{
String bestMove;
// Win if possible
bestMove = this.canPlayerWin(2);
if (bestMove != "")
return bestMove;
// Block if necessary
bestMove = this.canPlayerWin(1);
if (bestMove != "")
return bestMove;
// Center if it is open
if (board[4] == 2)
return "B2";
// First open corner
if (board[0] == 2)
return "A1";
if (board[2] == 2)
return "A3";
if (board[6] == 2)
return "C1";
if (board[8] == 2)
return "C3";
// First open edge
if (board[1] == 2)
return "A2";
if (board[3] == 2)
return "B1";
if (board[5] == 2)
return "B3";
if (board[7] == 2)
return "C2";
return ""; // The board is full
}
public String toString()
{
return " " +
getMark(board[0]) + " | " +
getMark(board[1]) + " | " +
getMark(board[2]) +
"\n-----------\n" +
" " +
getMark(board[3]) + " | " +
getMark(board[4]) + " | " +
getMark(board[5]) +
"\n-----------\n" +
" " +
getMark(board[6]) + " | " +
getMark(board[7]) + " | " +
getMark(board[8]);
}
private String getMark(int status)
{
if (status == 3)
return "X";
if (status == 5)
return "O";
return " ";
}
}
In the file newTicTacToe.java, after every game you are updating the count in the variables numWins, numDraws and numLosses.
You need to update the JLabels lblWins, lblDraws and lblLosses too.
In your reset function, also add:
lblWins.setText("Wins: " + numWins);
lblLosses.setText("Losses: " + numLosses);
lblDraws.setText("Draws: " + numDraws);
That should solve your problem.
You are never updating the JLabels after you update numLosses, numDraws, and numWins. Do this by using
lblWins.setText(Integer.toString(numWins));
lblLosses.setText(Integer.toString(numLosses));
lblDraws.setText(Integer.toString(numDraws));
at the appropriate places
I see that you are only updating the int variables, numWins, numDraws, numLosses.
Changing the value of a variable does not change your labels' texts. How can the computer know that your labels are "linked" with the variables?
The solution is easy, just as you said. You just need to set the text of the labels whenever you change the value of the variables.
numWins++;
lblWins.setText(Integer.toString(numWins));
"But I will forget to do this sometimes!" you shouted. That's why you should add "setter" methods like this one:
private void setNumWins(int value) {
numWins = value;
lblWins.setText(Integer.toString(value));
}
Now, you can just call setNumWins and the label will update as well:
setNumWins(numWins + 1);
Isn't this just wonderful?

Messed up my code terribly with throwing/catching exceptions and try...catch blocks

Alright, I know I messed up bad with catching and throwing exceptions, but I can't figure them out for the life of me. I think I'm mixing several different ways to do them. Can anyone guide me in the right direction (not looking for complete answer, just what the code is supposed to resemble)? It gets stuck on the "throw new ();" lines, and the catch blocks. Everything else seems to not have any issues. It's supposed to be an improvement on a previous project, http://pastebin.com/sjR0BZBY. you can run this if you'd like to see what the program is supposed to do if that helps.
public class Project6 extends JFrame
{
// Declaring variables
private JLabel enterLabel, resultsLabel, errorLabel;
private JTextField queryField, errorField;
private JButton goB, clearB;
private JTextArea textArea;
private Container c;
private JPanel panel;
// main method
public static void main(String[] args)
{
Project6 p6 = new Project6();
p6.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p6.setSize(new Dimension(455, 550));
p6.setVisible(true);
}
// creating JFrame
public Project6()
{
c = getContentPane();
c.setLayout(new FlowLayout());
setTitle("");
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
ButtonHandler handler = new ButtonHandler();
enterLabel = new JLabel("Enter query here:");
c.add(enterLabel);
queryField = new JTextField(35);
c.add(queryField);
goB = new JButton("GO!");
c.add(goB);
goB.addActionListener(handler);
resultsLabel = new JLabel("Results:");
c.add(resultsLabel);
textArea = new JTextArea(20, 30);
c.add(textArea);
errorLabel = new JLabel("-------------Error messages:");
c.add(errorLabel);
errorField = new JTextField(35);
c.add(errorField);
clearB = new JButton("Clear");
c.add(clearB);
clearB.addActionListener(handler);
}
// ActionListener for buttons
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
// Go! button
if (e.getSource() == goB){
String str = queryField.getText();
StringTokenizer tokens = new StringTokenizer(str, ", ");
int numToks = tokens.countTokens();
String[] tokenArray = new String[numToks];
int i = 0;
// creating all tokenizing, validations, and the works. Try and bear with it, it works but it's a rough trip
while (tokens.hasMoreTokens()){
// while loop to create tokens
while (tokens.hasMoreTokens()){
str = tokens.nextToken();
tokenArray[i] = str;
System.out.println(tokenArray[i]);
i++; }
// start if verifications, everything else
String query = tokenArray[3];
String optok = tokenArray[4];
String index = tokenArray[5];
String qField = queryField.getText();
try {
if (qField.equals(""))
throw new MissingInputException();
else {
if (numToks != 6)
throw new IncorrectFormatException();
else {
if (tokenArray[0].equalsIgnoreCase("Report"))
{
if (tokenArray[1].equalsIgnoreCase("all"))
{
if (tokenArray[2].equals("where"))
{
if (tokenArray[3].equals("basePrice") || tokenArray[3].equals("quality") || tokenArray[3].equals("numInStock"))
{
if (tokenArray[4].equals("<") || tokenArray[4].equals(">") || tokenArray[4].equals(">=")||tokenArray[4].equals("<=")||tokenArray[4].equals("=="))
{
if (query.equals("basePrice"))
{ BasePriceM(query, index, optok); }
else if (query.equals("quality"))
{ QualityM(query, index, optok); }
else if (query.equals("numInStock"))
{ NumInStockM(query, index, optok); }
}
else
throw new InvalidOperatorException();
}
else
throw new InvalidLValueException();
}
else
throw new InvalidQualifierException();
}
else
throw new InvalidSelectorException();
}
else
throw new IllegalStartOfQueryException();
}
}
} // end try
catch(MissingInputException aa)
{
errorField.setText("Enter an expression");
queryField.setText("");
}
catch(IncorrectFormatException ab)
{
errorField.setText("Error, field too large or small");
queryField.setText("");
}
catch(IllegalStartOfQueryException ac)
{
errorField.setText("Error, report expected");
queryField.setText("");
}
catch(InvalidSelectorException ad)
{
errorField.setText("Error, all expected");
queryField.setText("");
}
catch(InvalidQualifierException ae)
{
errorField.setText("Error, where expected");
queryField.setText("");
}
catch(InvalidLValueException af)
{
errorField.setText("Error, basePrice, Quality, numInStock expected");
queryField.setText("");
}
catch(InvalidOperatorException ag)
{
errorField.setText("Error, < > >= <= == expected");
queryField.setText("");
}
catch(NumberFormatException af)
{
}
}// end of while loop
} // end go button
// clear all button
if (e.getSource() == clearB)
{
queryField.setText("");
textArea.setText("");
errorField.setText("");
}
}
} // end buttons
// methods for printing
public void BasePriceM(String query, String index, String optok)
{
int pos = 0;
int index1 = index.indexOf(".", pos);
if (index1 > -1)
{
double b = Double.parseDouble(index);
if (b > 0.05 && b < 5400.0)
{printBasePrice(query, optok, b);}
else{
errorField.setText("Invalid query, must be between 0.05 and 5400.0");
queryField.setText(""); }}
}
public void QualityM(String query, String index, String optok)
{
int pos2 = 0;
int index2 = index.indexOf(".", pos2);
if (index2 == -1)
{
int n = Integer.parseInt(index);
if (n > 0)
{
printBasePrice(query, optok, n);
}
else{
errorField.setText("Invalid query, must be greater than 0");
queryField.setText(""); }}
}
public void NumInStock(String query, String index, String optok)
{
int pos2 = 0;
int index2 = index.indexOf(".", pos2);
if (index2 == -1)
{
int n = Integer.parseInt(index);
if (n > 0)
{
printBasePrice(query, optok, n);
}
else{
errorField.setText("Invalid query, must be greater than 0");
queryField.setText("");} }
}
public void printQuality(String query, String optok, int p)
{
textArea.append("Search for " + query +" "+ optok +" "+ p + "\n");
}
public void printBasePrice(String query, String optok, double b)
{
textArea.append("Search for " + query +" "+ optok +" "+ b + "\n");
}
public void printNumInStock(String query, String optok, int n)
{
textArea.append("Search for " + query +" "+ optok +" "+ n + "\n");
}
} // end program`enter code here`

Difficulty navigating 2d String array that correlates to another 2d int array

So I have a class that holds a bunch of stat info and such about a "gamer". I'm trying to implement a mock trophy system for certain stat goals that were achieved through an RNG.
I have a 2d int array that holds values for the grade/level of the trophy, that once achieved upgrades the trophy from bronze, to silver, etc and a corresponding 2d String array that holds the titles of such trophy levels. In testing what seemed to work with a now unused method actually provided trophies to only certain types. What I have now is a path I think I need to follow in order for this to work. I have a method called getBadges(int requestedStat) that takes an index value for another array to view that stats trophies. In that method is a for loop that compares the method's argument to both 2d arrays to determine if the stat's value (stored in another array) qualifies it for a bronze, silver, or gold trophy. My main problem is I'm getting lost in how to access these different data points in my 2d arrays without going out of the index's range. Not to mention when I set up a bunch of if-else statements my test output always produced the trophy's name, but no trophy level. Like such:
Healer: No Badge
Explorer: No Badge
Socialite: No Badge
Contributor: No Badge
As the skill points go up so should the badge levels (i.e. go from "No Badge" to "Bronze" etc). Is this a logic or syntax error? I'm super confused on what is happening in my code, despite my pseudo-code efforts. Here is the Gamer class:
package GamerProject;
import java.io.Serializable;
import java.util.Comparator;
public class Gamer implements Serializable, Comparable<Gamer> {
private String playerName;
private static final int HEALTH_POINTS_RESD = 23;
private static final int AREAS_VISITED = 200;
private static final int PLAYERS_ENCOUNTERED = 175;
private static final int MAPS_CREATED = 1500;
private static final int ITEMS_GATHERED = 20;
private static final int ITEMS_REPAIRED = 100;
private static final int ITEMS_MERGED = 125;
private static final int TOP_SCORES = 250;
private static final int DMG_POINTS_DEALT = 17;
private static final int MAPS_COMPLETED = 750;
private static final int LEVEL2 = 10000;
private static final int LEVEL3 = 25000;
private static final int LEVEL4 = 80000;
private static final int LEVEL5 = 150000;
private static final int LEVEL6 = 300000;
private static final int LEVEL7 = 1000000;
private static final int LEVEL8 = 2200000;
private static final int LEVEL9 = 4500000;
private static final int LEVEL10 = 10000000;
private static final int LEVEL11 = 20000000;
private static final int LEVEL12 = 35000000;
private final int[] gamerStatValues = new int[10];
private final int[] gamerActions = {HEALTH_POINTS_RESD, AREAS_VISITED, PLAYERS_ENCOUNTERED, MAPS_CREATED,
ITEMS_GATHERED, ITEMS_REPAIRED, ITEMS_MERGED, TOP_SCORES, DMG_POINTS_DEALT, MAPS_COMPLETED};
private final int[] expValues = {LEVEL2, LEVEL3, LEVEL4, LEVEL5, LEVEL6, LEVEL7,
LEVEL8, LEVEL9, LEVEL10, LEVEL11, LEVEL12};
private final int[][] badgePoints = {
{0, 2000, 10000, 30000, 100000, 200000},
{0, 50, 1000, 5000, 17000, 40000},
{0, 100, 1000, 2000, 10000, 30000},
{0, 3, 10, 20, 90, 150},
{0, 2000, 10000, 30000, 100000, 200000},
{0, 100, 1000, 5000, 15000, 40000},
{0, 100, 500, 2000, 10000, 40000},
{0, 20, 200, 1000, 5000, 20000},
{0, 2000, 10000, 30000, 100000, 300000},
{0, 10, 50, 200, 500, 5000}};
private final String[] badgeTitles = {"Healer: ", "Explorer: ", "Socialite: ", "Contributor: ",
"Hoarder: ", "Fixer: ", "Joiner: ", "Leader: ", "Punisher: ", "Obsessed: ",};
private final String[] badgeRanks = {"No Badge ", "Tin ", "Bronze ", "Silver ", "Gold ", "Platinum "};
Gamer() {
playerName = "";
}
public int getTotalExp() {
int totalExp = 0;
for (int i = 0; i < gamerStatValues.length; i++) {
totalExp += (gamerStatValues[i] * gamerActions[i]);
}
return totalExp;
}
public int getLevel() {
int playerLevel = 1;
int totalExp = getTotalExp();
for (int i = 0; i < expValues.length; i++) {
if (totalExp >= expValues[i]) {
playerLevel += 1;
//System.out.println(getTotalExp());
}
}
return playerLevel;
}
public String getBadge(int requestedStat) {
String badgeOutput = "";
//index = 0;
if (requestedStat >= 0 && requestedStat <=9) {
for (int i = 0; i < badgeRanks.length; i++) {//not sure how to get around going out of the array bounds
if (gamerActions[requestedStat] >= badgePoints[requestedStat][i]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 1]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i];
} else if (gamerActions[requestedStat] >= badgePoints[requestedStat][i+1]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 2]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i+1];
}
}
//did this as an extraneous solution. Still doesn't work
// if (gamerActions[requestedStat] >= badgePoints[requestedStat][index]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 1]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+1]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 2]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+1];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+2]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 3]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+2];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+3]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 4]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+3];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+4]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 5]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+4];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+5]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 6]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+5];
// } else {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+6];
// }
//
} else {
badgeOutput = "No Badges Available";
}
return badgeOutput;
}
//Incomplete Method
public String getBadges() {
String badgeOutput = "Badges: ";
for (int i = 0; i < badgeTitles.length; i++) {
// if (gamerActions[i]) {
//
// }
}
return badgeOutput;
}
public String getPlayerName() {
return playerName;
}
public int getHealthPointsResd() {
return gamerStatValues[0];
}
public int getAreasVisited() {
return gamerStatValues[1];
}
public int getPlayersEncountered() {
return gamerStatValues[2];
}
public int getMapsCreated() {
return gamerStatValues[3];
}
public int getItemsGathered() {
return gamerStatValues[4];
}
public int getItemsRepaired() {
return gamerStatValues[5];
}
public int getItemsMerged() {
return gamerStatValues[6];
}
public int getTopScores() {
return gamerStatValues[7];
}
public int getDmgPointsDealt() {
return gamerStatValues[8];
}
public int getMapsCompleted() {
return gamerStatValues[9];
}
//Unused Method
public void updateRandomGamerAction(int intValue) {
if (intValue == 0) {
gamerActions[0]+=1;
} else if (intValue == 1) {
gamerActions[1]+=1;
} else if (intValue == 2) {
gamerActions[2]+=1;
} else if (intValue == 3) {
gamerActions[3]+=1;
} else if (intValue == 4) {
gamerActions[4]+=1;
} else if (intValue == 5) {
gamerActions[5]+=1;
} else if (intValue == 6) {
gamerActions[6]+=1;
} else if (intValue == 7) {
gamerActions[7]+=1;
} else if (intValue == 8) {
gamerActions[8]+=1;
} else {
gamerActions[9]+=1;
}
}
public String setPlayerName(String playerName) {
this.playerName = playerName;
return this.playerName;
}
public int setHealthPointsResd(int healthPointsResd) {
if (healthPointsResd >= 0) {
gamerStatValues[0] = healthPointsResd;
return gamerStatValues[0];
} else {
return gamerStatValues[0];
}
}
public int setAreasVisited(int areasVisited) {
if (areasVisited >= 0) {
gamerStatValues[1] = areasVisited;
return gamerStatValues[1];
} else {
return gamerStatValues[1];
}
}
public int setPlayersEncountered(int playersEncountered) {
if (playersEncountered >= 0) {
gamerStatValues[2] = playersEncountered;
return gamerStatValues[2];
} else {
return gamerStatValues[2];
}
}
public int setMapsCreated(int mapsCreated) {
if (mapsCreated >= 0) {
gamerStatValues[3] = mapsCreated;
return gamerStatValues[3];
} else {
return gamerStatValues[3];
}
}
public int setItemsGathered(int itemsGathered) {
if (itemsGathered >= 0) {
gamerStatValues[4] = itemsGathered;
return gamerStatValues[4];
} else {
return gamerStatValues[4];
}
}
public int setItemsRepaired(int itemsRepaired) {
if (itemsRepaired >= 0) {
gamerStatValues[5] = itemsRepaired;
return gamerStatValues[5];
} else {
return gamerStatValues[5];
}
}
public int setItemsMerged(int itemsMerged) {
if (itemsMerged >= 0) {
gamerStatValues[6] = itemsMerged;
return gamerStatValues[6];
} else {
return gamerStatValues[6];
}
}
public int setTopScores(int topScores) {
if (topScores >= 0) {
gamerStatValues[7] = topScores;
return gamerStatValues[7];
} else {
return gamerStatValues[7];
}
}
public int setDmgPointsDealt(int dmgPointsDealt) {
if (dmgPointsDealt >= 0) {
gamerStatValues[8] = dmgPointsDealt;
return gamerStatValues[8];
} else {
return gamerStatValues[8];
}
}
public int setMapsCompleted(int mapsCompleted) {
if (mapsCompleted >= 0) {
gamerStatValues[9] = mapsCompleted;
return gamerStatValues[9];
} else {
return gamerStatValues[9];
}
}
public void setStatsToZero(){
for (int i = 0; i < gamerActions.length; i++) {
gamerActions[i] = 0;
}
}
public String statsString() {
return "Stats: " + "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
public String shortDecription() {
return String.format("%16s: Level %2d, Experience Points: %,10d",
playerName, this.getLevel(), this.getTotalExp());
}
#Override
public String toString() {
return "Gamer{" + "Player Name = " + playerName + " Player Stats: "
+ "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
#Override
public int compareTo(Gamer player) {
if (this.getTotalExp() > player.getTotalExp()) {
return 1;
} else if (this.getTotalExp() == player.getTotalExp()) {
return 0;
} else {
return -1;
}
}
}
and here is the driver I'm testing it with:
package GamerProject;
import java.util.Random;
public class Program7Driver {
private static final int rngRange = 10;
private static final Gamer[] gamers = new Gamer[10];
private static final String[] gamerNames = {"BestGamer99", "CdrShepardN7",
"Gandalf_The_Cool", "SharpShooter01", "TheDragonborn", "SithLord01",
"MrWolfenstien", "Goldeneye007", "DungeonMaster91", "MasterThief","TheDarkKnight"};
public static void main(String[] args) {
Random rand = new Random();
for (int i = 0; i < gamers.length; i++) {
gamers[i] = new Gamer();
gamers[i].setPlayerName(gamerNames[i]);
gamers[i].setStatsToZero();
}
// for (int i = 0; i < 200000; i++) {
// int rng = rand.nextInt(rngRange);
// gamers[rng].setRandomGamerAction(rng);
// }
int count = 0;
for (int i = 0; i < 20000; i++) {
int rng = rand.nextInt(rngRange);
System.out.println(gamers[0].getBadge(count));
//System.out.println(gamers[0].toString());
//gamers[0].updateRandomGamerAction(rng);
if (rng == 0) {
gamers[0].setHealthPointsResd(gamers[0].getHealthPointsResd()+1);
} else if (rng == 1) {
gamers[0].setAreasVisited(gamers[0].getAreasVisited()+1);
} else if (rng == 2) {
gamers[0].setPlayersEncountered(gamers[0].getPlayersEncountered()+1);
} else if (rng == 3) {
gamers[0].setMapsCreated(gamers[0].getMapsCreated()+1);
} else if (rng == 4) {
gamers[0].setItemsGathered(gamers[0].getItemsGathered()+1);
} else if (rng == 5) {
gamers[0].setItemsRepaired(gamers[0].getItemsRepaired()+1);
} else if (rng == 6) {
gamers[0].setItemsMerged(gamers[0].getItemsMerged()+1);
} else if (rng == 7) {
gamers[0].setTopScores(gamers[0].getTopScores()+1);
} else if (rng == 8) {
gamers[0].setDmgPointsDealt(gamers[0].getDmgPointsDealt()+1);
} else {
gamers[0].setMapsCompleted(gamers[0].getMapsCompleted()+1);
}
count += 1;
if (count == 10) {
count -= 10;
}
// System.out.println(gamers[i].statsString());
}
}
}
Okay, I made some changes. See if this does what you were wanting:
package GamerProject;
import java.io.Serializable;
import java.util.Comparator;
public class Gamer implements Serializable, Comparable<Gamer> {
/**
*
*/
private static final long serialVersionUID = 1L;
private String playerName;
private static final int HEALTH_POINTS_RESD = 23;
private static final int AREAS_VISITED = 200;
private static final int PLAYERS_ENCOUNTERED = 175;
private static final int MAPS_CREATED = 1500;
private static final int ITEMS_GATHERED = 20;
private static final int ITEMS_REPAIRED = 100;
private static final int ITEMS_MERGED = 125;
private static final int TOP_SCORES = 250;
private static final int DMG_POINTS_DEALT = 17;
private static final int MAPS_COMPLETED = 750;
private static final int LEVEL2 = 10000;
private static final int LEVEL3 = 25000;
private static final int LEVEL4 = 80000;
private static final int LEVEL5 = 150000;
private static final int LEVEL6 = 300000;
private static final int LEVEL7 = 1000000;
private static final int LEVEL8 = 2200000;
private static final int LEVEL9 = 4500000;
private static final int LEVEL10 = 10000000;
private static final int LEVEL11 = 20000000;
private static final int LEVEL12 = 35000000;
private final int[] gamerStatValues = new int[10];
private final int[] gamerActions = {HEALTH_POINTS_RESD, AREAS_VISITED, PLAYERS_ENCOUNTERED, MAPS_CREATED,
ITEMS_GATHERED, ITEMS_REPAIRED, ITEMS_MERGED, TOP_SCORES, DMG_POINTS_DEALT, MAPS_COMPLETED};
private final int[] expValues = {LEVEL2, LEVEL3, LEVEL4, LEVEL5, LEVEL6, LEVEL7,
LEVEL8, LEVEL9, LEVEL10, LEVEL11, LEVEL12};
private final int[][] badgePoints = {
{0, 2000, 10000, 30000, 100000, 200000},
{0, 50, 1000, 5000, 17000, 40000},
{0, 100, 1000, 2000, 10000, 30000},
{0, 3, 10, 20, 90, 150},
{0, 2000, 10000, 30000, 100000, 200000},
{0, 100, 1000, 5000, 15000, 40000},
{0, 100, 500, 2000, 10000, 40000},
{0, 20, 200, 1000, 5000, 20000},
{0, 2000, 10000, 30000, 100000, 300000},
{0, 10, 50, 200, 500, 5000}};
private final String[] badgeTitles = {"Healer: ", "Explorer: ", "Socialite: ", "Contributor: ",
"Hoarder: ", "Fixer: ", "Joiner: ", "Leader: ", "Punisher: ", "Obsessed: ",};
private final String[] badgeRanks = {"No Badge ", "Tin ", "Bronze ", "Silver ", "Gold ", "Platinum "};
Gamer() {
playerName = "";
}
public int getTotalExp() {
int totalExp = 0;
for (int i = 0; i < gamerStatValues.length; i++) {
totalExp += (gamerStatValues[i] * gamerActions[i]);
}
return totalExp;
}
public int getLevel() {
int playerLevel = 1;
int totalExp = getTotalExp();
for (int i = 0; i < expValues.length; i++) {
if (totalExp >= expValues[i]) {
playerLevel += 1;
//System.out.println(getTotalExp());
}
}
return playerLevel;
}
public String getBadge(int requestedStat) {
String badgeOutput = "";
//index = 0;
if (requestedStat >= 0 && requestedStat <=9) {
for (int i = 0; i < badgeRanks.length; i++) {//not sure how to get around going out of the array bounds
if (gamerActions[requestedStat] >= badgePoints[requestedStat][i]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 1]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i];
} else if (gamerActions[requestedStat] >= badgePoints[requestedStat][i+1]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 2]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i+1];
}
}
//did this as an extraneous solution. Still doesn't work
// if (gamerActions[requestedStat] >= badgePoints[requestedStat][index]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 1]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+1]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 2]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+1];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+2]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 3]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+2];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+3]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 4]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+3];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+4]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 5]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+4];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+5]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 6]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+5];
// } else {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+6];
// }
//
} else {
badgeOutput = "No Badges Available";
}
return badgeOutput;
}
//Incomplete Method
public String getBadges() {
String badgeOutput = "Badges: ";
for (int i = 0; i < badgeTitles.length; i++) {
// if (gamerActions[i]) {
//
// }
}
return badgeOutput;
}
public String getPlayerName() {
return playerName;
}
public int getHealthPointsResd() {
return gamerStatValues[0];
}
public int getAreasVisited() {
return gamerStatValues[1];
}
public int getPlayersEncountered() {
return gamerStatValues[2];
}
public int getMapsCreated() {
return gamerStatValues[3];
}
public int getItemsGathered() {
return gamerStatValues[4];
}
public int getItemsRepaired() {
return gamerStatValues[5];
}
public int getItemsMerged() {
return gamerStatValues[6];
}
public int getTopScores() {
return gamerStatValues[7];
}
public int getDmgPointsDealt() {
return gamerStatValues[8];
}
public int getMapsCompleted() {
return gamerStatValues[9];
}
//Unused Method
public void updateRandomGamerAction(int intValue) {
if (intValue == 0) {
gamerActions[0]+=1;
} else if (intValue == 1) {
gamerActions[1]+=1;
} else if (intValue == 2) {
gamerActions[2]+=1;
} else if (intValue == 3) {
gamerActions[3]+=1;
} else if (intValue == 4) {
gamerActions[4]+=1;
} else if (intValue == 5) {
gamerActions[5]+=1;
} else if (intValue == 6) {
gamerActions[6]+=1;
} else if (intValue == 7) {
gamerActions[7]+=1;
} else if (intValue == 8) {
gamerActions[8]+=1;
} else {
gamerActions[9]+=1;
}
}
public String setPlayerName(String playerName) {
this.playerName = playerName;
return this.playerName;
}
public int setHealthPointsResd(int healthPointsResd) {
if (healthPointsResd >= 0) {
gamerStatValues[0] = healthPointsResd;
return gamerStatValues[0];
} else {
return gamerStatValues[0];
}
}
public int setAreasVisited(int areasVisited) {
if (areasVisited >= 0) {
gamerStatValues[1] = areasVisited;
return gamerStatValues[1];
} else {
return gamerStatValues[1];
}
}
public int setPlayersEncountered(int playersEncountered) {
if (playersEncountered >= 0) {
gamerStatValues[2] = playersEncountered;
return gamerStatValues[2];
} else {
return gamerStatValues[2];
}
}
public int setMapsCreated(int mapsCreated) {
if (mapsCreated >= 0) {
gamerStatValues[3] = mapsCreated;
return gamerStatValues[3];
} else {
return gamerStatValues[3];
}
}
public int setItemsGathered(int itemsGathered) {
if (itemsGathered >= 0) {
gamerStatValues[4] = itemsGathered;
return gamerStatValues[4];
} else {
return gamerStatValues[4];
}
}
public int setItemsRepaired(int itemsRepaired) {
if (itemsRepaired >= 0) {
gamerStatValues[5] = itemsRepaired;
return gamerStatValues[5];
} else {
return gamerStatValues[5];
}
}
public int setItemsMerged(int itemsMerged) {
if (itemsMerged >= 0) {
gamerStatValues[6] = itemsMerged;
return gamerStatValues[6];
} else {
return gamerStatValues[6];
}
}
public int setTopScores(int topScores) {
if (topScores >= 0) {
gamerStatValues[7] = topScores;
return gamerStatValues[7];
} else {
return gamerStatValues[7];
}
}
public int setDmgPointsDealt(int dmgPointsDealt) {
if (dmgPointsDealt >= 0) {
gamerStatValues[8] = dmgPointsDealt;
return gamerStatValues[8];
} else {
return gamerStatValues[8];
}
}
public int setMapsCompleted(int mapsCompleted) {
if (mapsCompleted >= 0) {
gamerStatValues[9] = mapsCompleted;
return gamerStatValues[9];
} else {
return gamerStatValues[9];
}
}
public void setStatsToZero(){
for (int i = 0; i < gamerActions.length; i++) {
gamerActions[i] = 0;
}
}
public String statsString() {
return "Stats: " + "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
public String shortDecription() {
return String.format("%16s: Level %2d, Experience Points: %,10d",
playerName, this.getLevel(), this.getTotalExp());
}
#Override
public String toString() {
return "Gamer{" + "Player Name = " + playerName + " Player Stats: "
+ "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
#Override
public int compareTo(Gamer player) {
if (this.getTotalExp() > player.getTotalExp()) {
return 1;
} else if (this.getTotalExp() == player.getTotalExp()) {
return 0;
} else {
return -1;
}
}
}
And the other:
package GamerProject;
import java.util.Random;
public class Program7Driver {
private static final int rngRange = 10;
private static final Gamer[] gamers = new Gamer[10];
private static final String[] gamerNames = {"BestGamer99", "CdrShepardN7",
"Gandalf_The_Cool", "SharpShooter01", "TheDragonborn", "SithLord01",
"MrWolfenstien", "Goldeneye007", "DungeonMaster91", "MasterThief","TheDarkKnight"};
public static void main(String[] args) {
Random rand = new Random();
for (int i = 0; i < gamers.length; i++) {
gamers[i] = new Gamer();
gamers[i].setPlayerName(gamerNames[i]);
gamers[i].setStatsToZero();
}
// for (int i = 0; i < 200000; i++) {
// int rng = rand.nextInt(rngRange);
// gamers[rng].setRandomGamerAction(rng);
// }
int count = 0;
for (int i = 0; i < gamers.length; i++) {
int rng = rand.nextInt(rngRange);
System.out.println(gamers[i]);
//System.out.println(gamers[0].toString());
//gamers[0].updateRandomGamerAction(rng);
if (rng == 0) {
gamers[0].setHealthPointsResd(gamers[0].getHealthPointsResd()+1);
} else if (rng == 1) {
gamers[0].setAreasVisited(gamers[0].getAreasVisited()+1);
} else if (rng == 2) {
gamers[0].setPlayersEncountered(gamers[0].getPlayersEncountered()+1);
} else if (rng == 3) {
gamers[0].setMapsCreated(gamers[0].getMapsCreated()+1);
} else if (rng == 4) {
gamers[0].setItemsGathered(gamers[0].getItemsGathered()+1);
} else if (rng == 5) {
gamers[0].setItemsRepaired(gamers[0].getItemsRepaired()+1);
} else if (rng == 6) {
gamers[0].setItemsMerged(gamers[0].getItemsMerged()+1);
} else if (rng == 7) {
gamers[0].setTopScores(gamers[0].getTopScores()+1);
} else if (rng == 8) {
gamers[0].setDmgPointsDealt(gamers[0].getDmgPointsDealt()+1);
} else {
gamers[0].setMapsCompleted(gamers[0].getMapsCompleted()+1);
}
count += 1;
if (count == 10) {
count -= 10;
}
// System.out.println(gamers[i].statsString());
}
}
}

Reacting to a specific char - TCP and char[][] issue

I'm creating a TCP game of Battleship in Java, and as I've made some functions work, methods that used to work no longer work.
Here's what's happening when it's a users turn. A bomb being dropped on 2 diffrent char[][], where clientGrid is the actual grid where the client has his ships. It's on this grid where the dropBomb method is being printed, and tells us whether a bomb has hit or not. clientDamage is just an overview for the server to see where he has previously dropped bombs.
if (inFromServer.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(clientDamage));
}
Here's the drop bomb method. It's proved to work before, however I have made some small changes to it. However I can't see why it wouldn't work. + indicates that there is a ship, x indicates that the target already has been bombed, and the else is ~, which is water. The method always returns "Nothing was hit on this coordinate...", and I can't seem to figure out why?
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
board[row][col] = 'x';
return "Ship has been hit!";
} else if (board[row][col] == 'x') {
return "Already bombed.";
} else {
board[row][col] = 'x';
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
}
Here is the full code... can someone please point out what I'm missing?
//server = player 1
//client = player 2
public class BattleshipGame {
public static ArrayList<Ship> fleet;
public static InetAddress clientAddress;
public static BattleshipGame battleship;
private final static int gridSize = 11;
public final static int numberOfShips = 3;
public static char[][] serverGrid;
public static char[][] clientGrid;
public static char[][] serverDamage;
public static char[][] clientDamage;
private int whosTurn;
private int whoStarts;
public static int count;
public static int bombCount;
public BattleshipGame() {
whoStarts = 0;
start();
showShipList();
}
public static String printBoard(char[][] board) {
String out = "";
for (int i = 1; i < board.length; i++) {
for (int j = 1; j < board.length; j++) {
out += board[j][i];
}
out += '\n';
}
return out;
}
public void start() {
Random rand = new Random();
if (rand.nextBoolean()) {
whoStarts = 1;
whosTurn = 1;
} else {
whoStarts = 2;
whosTurn = 2;
}
whoStarts = 1;
whosTurn = 1;
System.out.println("Player " + whoStarts + " starts\n");
}
public void initializeGrid(int playerNo) {
serverGrid = new char[gridSize][gridSize];
for (int i = 0; i < serverGrid.length; i++) {
for (int j = 0; j < serverGrid.length; j++) {
serverGrid[i][j] = '~';
}
}
serverDamage = new char[gridSize][gridSize];
for (int i = 0; i < serverDamage.length; i++) {
for (int j = 0; j < serverDamage.length; j++) {
serverDamage[i][j] = '~';
}
}
clientGrid = new char[gridSize][gridSize];
for (int i = 0; i < clientGrid.length; i++) {
for (int j = 0; j < clientGrid.length; j++) {
clientGrid[i][j] = '~';
}
}
clientDamage = new char[gridSize][gridSize];
for (int i = 0; i < clientDamage.length; i++) {
for (int j = 0; j < clientDamage.length; j++) {
clientDamage[i][j] = '~';
}
}
if (playerNo == 1) {
System.out.println("\nYour grid (player 1):\n"
+ printBoard(serverGrid));
} else if (playerNo == 2) {
System.out.println("\nYour grid (player 2):\n"
+ printBoard(clientGrid));
} else {
System.out.println("No such player.");
}
}
public static void deployShip(char[][] board, Ship ship, char direction,
int x, int y) {
if (direction == 'H') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x + i][y] = '+';
}
System.out
.println("Ship has been placed horizontally on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
} else if (direction == 'V') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x][y + i] = '+';
}
System.out
.println("Ship has been placed vertically on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
}
}
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Ship has been hit!";
}
if (board[row][col] == 'x') {
System.out.println(board[row][col]);
bombCount++;
return "Already bombed.";
}
if (board[row][col] == '~') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
return "";
}
public void showShipList() {
System.out
.println("Choose ships to add to your fleet from the following list ("
+ numberOfShips + " ships allowed):");
ArrayList<Ship> overview = new ArrayList<Ship>();
Ship ac = new Ship("Aircraft carrier", 5, false);
Ship bs = new Ship("Battleship", 4, false);
Ship sm = new Ship("Submarine", 3, false);
Ship ds = new Ship("Destroyer", 3, false);
Ship sp = new Ship("Patrol Boat", 2, false);
overview.add(ac);
overview.add(bs);
overview.add(sm);
overview.add(ds);
overview.add(sp);
for (int i = 0; i < overview.size(); i++) {
System.out.println(i + 1 + ". " + overview.get(i));
}
}
public static ArrayList<Ship> createFleet(ArrayList<Ship> fleet, int choice) {
if (count < numberOfShips && choice > 0 && choice < 6) {
if (choice == 1) {
Ship ac = new Ship("Aircraft carrier", 5, false);
fleet.add(ac);
count++;
System.out.println("Aircraft carrier has been added to fleet.");
} else if (choice == 2) {
Ship bs = new Ship("Battleship", 4, false);
fleet.add(bs);
count++;
System.out.println("Battleship has been added to fleet.");
} else if (choice == 3) {
Ship sm = new Ship("Submarine", 3, false);
fleet.add(sm);
count++;
System.out.println("Submarine has been added to fleet.");
} else if (choice == 4) {
Ship ds = new Ship("Destroyer", 3, false);
fleet.add(ds);
count++;
System.out.println("Destroyer has been added to fleet.");
} else if (choice == 5) {
Ship sp = new Ship("Patrol Boat", 2, false);
fleet.add(sp);
count++;
System.out.println("Patrol boat has been added to fleet.");
}
} else {
System.out.println("Not an option.");
}
System.out.println("\nYour fleet now contains:");
for (Ship s : fleet) {
System.out.println(s);
}
return fleet;
}
}
public class TCPServer extends BattleshipGame {
private static final int playerNo = 1;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
ServerSocket serverSocket = new ServerSocket(6780);
Socket socket = serverSocket.accept();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
Scanner scan = new Scanner(System.in);
while (true) {
if (inFromServer.ready()) {
setup(scan, playerNo);
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
System.out.println(printBoard(clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
printBoard(clientDamage);
}
if (inFromClient.ready()) {
System.out.println(inFromClient.readLine());
System.out.println(printBoard(serverGrid));
}
}
// socket.close();
// serverSocet.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(serverGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(serverGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
public class TCPClient extends BattleshipGame {
private static final int playerNo = 2;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
Socket socket = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 6780);
DataOutputStream dataOutputStream = new DataOutputStream(
socket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
setup(scan, playerNo);
while (true) {
if (inFromClient.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, serverGrid));
dropBomb(x, y, serverDamage);
dataOutputStream.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(serverDamage));
}
if (inFromServer.ready()) { // modtag data fra server
System.out.println(inFromServer.readLine());
System.out.println(printBoard(clientGrid));
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(clientGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(clientGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
package Battleships;
public class Ship {
private String name;
private int size;
private boolean isDestroyed;
public Ship(String n, int s, boolean d) {
this.name = n;
this.size = s;
this.isDestroyed = d;
}
public String getName() {
String output = "";
output = "[" + name + "]";
return output;
}
public int getSize() {
return size;
}
public String toString() {
String output = "";
output = "[" + name + ", " + size + ", " + isDestroyed + "]";
return output;
}
}

Array null pointer exception error

I am continuing with my project for school and have seemed to encounter another error. So what is happening is basically I am receiving a null pointer exception even though the code looks fine. I believe something is wrong with my array, and even after hours of searching I can't seem to find the error. Once again, any help/solution would be greatly appreciated.
import java.util.*;
public class library {
private static students stu1 = new students(65435, "Bob", "Ted");
private static students stu2 = new students(45546, "Guy", "Sid");
private static students stu3 = new students(78688, "Tim", "Cas");
private static students stu4 = new students(45387, "Guy", "Jim");
private static students stu5 = new students(12367, "Dom", "Lam");
private static students stu6 = new students(45905, "Kid", "Loo");
private static students stu7 = new students(65484, "Mut", "Hum");
private static students stu8 = new students(34578, "Kim", "Hay");
private static students stu9 = new students(20457, "Roy", "Boy");
private static students stu0 = new students(15678, "Kil", "Bil");
private static students[] studentArray;
private static students[] stuArrayAlt;
private static boolean firstArrayStu = true;
// private static books bookName = new books("title",
// "author","category","isbn", cost, rating out of 10);
private static books book1 = new books(
"Harry Potter and the Deathly Hallows", "JK Rowling", "fantasy",
"9780739360385", 30.00, 9.0);
private static books book2 = new books("Angels and Demons", "Dan Brown",
"fiction", "9780828855495", 25.00, 8.5);
private static books book3 = new books("The Hunger Games",
"Suzanne Collins", "science fiction", "9780439023481", 20.00, 8.0);
private static books book4 = new books("A Game of Thrones",
"George R R Martin", "fantasy", "9780002245845", 54.50, 12.5);
private static books book5 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book6 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book7 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book8 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book9 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books book0 = new books("title2", "author2", "category2",
"isbn2", 54.50, 12.5);
private static books[] bookArray;
private static books[] bookArrayAlt;
private static boolean firstArrayBook;
private static int year1;
private static int month1;
private static int date1;
public library() {
bookArray = new books[] { book1, book2, book3, book4, book5, book6,
book7, book8, book9, book0 };
firstArrayBook = true;
studentArray = new students[] { stu1, stu2, stu3, stu4, stu5, stu6,
stu7, stu8, stu9, stu0 };
firstArrayStu = true;
}
public static void main(String[] args) {
// System.out.println(stu1.getStuNum() + " " + stu1.getFirstName() +
// " "+ stu1.getLastName());
// books[] bookReturn = stu1.insertBook(book1);
// System.out.println(book1.getCheckInLibrary());
// System.out.println(book1.getCheckInLibrary());
// System.out.println(bookReturn[0].getName());
// books[] bookReturn2 = stu1.insertBook(book2);
// System.out.println(book2.getCheckInLibrary());
// System.out.println(book2.getCheckInLibrary());
// stu1.insertBook(book1);
// checkOutBook(stu1,book1);
// System.out.println(stu1);
// stu1=null;
// System.out.println(stu1);
/*
* stu1.lostBookFine(book1); System.out.println(stu1.getFineBalance());
* stu1.lostBookFine(book2); System.out.println(stu1.getFineBalance());
*/
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[(a.length) + 1];
System.arraycopy(a, 0, b, 0, a.length);
b[a.length] = 6;
// for(int i=0;i<b.length;i++)
// {
// System.out.println(b[i]);
// }
/*
* int[] c = new int[]{1,2,3,4,5,6}; b = new int[(c.length)+1];
*
* System.arraycopy( c, 0, b, 0, c.length ); b[c.length]=7;
*
* for(int i=0;i<b.length;i++) { System.out.println(b[i]); }
*/
// int[] date = enterDate();
// int[] date2 = book1.addTwoWeeks(date);
// int[]date2= book1.getDateDue();
System.out.println(studentArray[0].getFirstName());
//boolean array=checkStuNum(45456);
//System.out.println(array);
//students[]array=lookUpLastName("sid");
//array[0].getFirstName();
}
public static void returnBook(students borrower, books bookReturn) {
}
public static books[] lookUpTitleBooks(String title)// //////////////interchange
// the array-boolean
// firstArrayBook--two
// if statements
{
int counter = 0;
for (int i = 0; i < bookArray.length; i++) {
if (title.equalsIgnoreCase(bookArray[i].getTitle())
|| ((bookArray[i].getTitle().toLowerCase())).contains(title
.toLowerCase())) {
counter++;
}
}
books[] booksLookUp = new books[counter];
int counterS = 0;
for (int i = 0; i < bookArray.length; i++) {
if (title.equalsIgnoreCase(bookArray[i].getTitle())
|| ((bookArray[i].getTitle().toLowerCase())).contains(title
.toLowerCase())) {
booksLookUp[counterS] = bookArray[i];
counterS++;
}
}
return booksLookUp;
}
// look up last name of student
public static students[] lookUpLastName(String lName) {
students[] studentlName = new students[1] ;
if (firstArrayStu == true) {
int counter = 0;
System.out.println("check");
for (int i = 0; i < studentArray.length; i++) {
if (lName.equalsIgnoreCase(studentArray[i].getLastName()) || ((studentArray[i].getLastName()).contains(lName.toLowerCase())) ){
counter++;
System.out.println("check if");
}
System.out.println("check for");
}
studentlName = new students[counter];
int counterS = 0;
for (int i = 0; i < studentArray.length; i++) {
if (lName.equalsIgnoreCase(studentArray[i].getFirstName())
|| ((studentArray[i].getFirstName().toLowerCase()))
.contains(lName.toLowerCase())) {
studentlName[counterS] = studentArray[i];
counterS++;
}
}
}
if (firstArrayStu == false) {
int counter = 0;
for (int i = 0; i < stuArrayAlt.length; i++) {
if (lName.equalsIgnoreCase(stuArrayAlt[i].getFirstName())
|| ((stuArrayAlt[i].getFirstName().toLowerCase()))
.contains(lName.toLowerCase())) {
counter++;
}
}
studentlName = new students[counter];
int counterS = 0;
for (int i = 0; i < stuArrayAlt.length; i++) {
if (lName.equalsIgnoreCase(stuArrayAlt[i].getFirstName())
|| ((stuArrayAlt[i].getFirstName().toLowerCase()))
.contains(lName.toLowerCase())) {
studentlName[counterS] = stuArrayAlt[i];
counterS++;
}
}
}
return studentlName;
}
public static void checkOutBook(students borrower, books bookBorrow) {
boolean canBorrow1 = checkFine(borrower);
boolean canBorrow2 = checkBorrowedBooks(borrower);
boolean canBorrow3 = checkBorrowedBooks(bookBorrow);
if (canBorrow1 == false) {
System.out.println("Your fine is too damn high");// alert window and
// redirect to
// main menu-so
// he/she can
// pay it if he
// wants to
}
if (canBorrow2 == false) {
System.out.println("Your already have 3 books checked out");// alert
// window
// and
// redirect
// to
// main
// menu-
// so
// he/she
// can
// return
// a
// book
// if he
// wants
// to
}
if (canBorrow1 == false) {
System.out.println("This book has been checkd out");// alert window
// and redirect
// to main menu-
// so he/she can
// look for
// another book
// and check it
// out
}
if (canBorrow1 && canBorrow2 && canBorrow3) {
borrower.insertBook(bookBorrow);
bookBorrow.checkOutStatusChange();
// alert window to show successful check out and redirect to main
// menu
}
}
public static boolean checkFine(students borrower) {
boolean canBorrow1 = borrower.checkBorrowedBooks(borrower
.getBookArray());
return canBorrow1;
}
public static boolean checkBorrowedBooks(students borrower) {
boolean canBorrow2 = borrower.checkFine(borrower);
return canBorrow2;
}
public static boolean checkBorrowedBooks(books bookBorrow) {
boolean canBorrow3 = bookBorrow.getCheckInLibrary();
return canBorrow3;
}
public static int[] enterDate() {
Scanner input = new Scanner(System.in);
boolean dateTrue = false;
int year, month, date;
while (dateTrue == false) {
System.out.println("Enter year");
year = input.nextInt();
System.out.println("Enter month");
month = input.nextInt();
System.out.println("Enter date");
date = input.nextInt();
// checking first date----------------------------------------
year1 = ((year >= 2010) ? year : 0);
month1 = ((month >= 1 && month <= 12) ? month : 0);
if (month1 == 1) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 2 && (year1 % 4) != 0) {
date1 = ((date >= 1 && date <= 28) ? date : 0);
}
if (month1 == 2 && (year1 % 4) == 0) {
date1 = ((date >= 1 && date <= 29) ? date : 0);
}
if (month1 == 3) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 4) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 5) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 6) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 7) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 8) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 9) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 10) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 11) {
date1 = ((date >= 1 && date <= 30) ? date : 0);
}
if (month1 == 12) {
date1 = ((date >= 1 && date <= 31) ? date : 0);
}
if (month1 == 0 || date1 == 0 || year1 == 0) {
// do nothing boolean remains false
// put alert window here
} else {
dateTrue = true;
}
}
int[] dates = { year1, month1, date1 };
return dates;
}
public void createStudent(int stuNum, String fName, String lName) {
if (firstArrayStu == true) {
for (int i = 0; i < studentArray.length; i++) {
if (studentArray[i] == null) {
studentArray[i] = new students(stuNum, fName, lName);
} else if (i == (studentArray.length - 1)) {
stuArrayAlt = new students[studentArray.length + 1];
System.arraycopy(studentArray, 0, stuArrayAlt, 0,
studentArray.length);
stuArrayAlt[studentArray.length] = new students(stuNum,
fName, lName);
firstArrayStu = false;
}
}
} else if (firstArrayStu == false) {
for (int i = 0; i < stuArrayAlt.length; i++) {
if (stuArrayAlt[i] == null) {
stuArrayAlt[i] = new students(stuNum, fName, lName);
} else if (i == (stuArrayAlt.length - 1)) {
studentArray = new students[stuArrayAlt.length + 1];
System.arraycopy(stuArrayAlt, 0, stuArrayAlt, 0,
stuArrayAlt.length);
studentArray[stuArrayAlt.length] = new students(stuNum,
fName, lName);
firstArrayStu = true;
}
}
}
}
public static void createBook(String name, String author, String category,
String isbn, double cost, double sRating) {
if (firstArrayBook == true) {
for (int i = 0; i < bookArray.length; i++) {
if (bookArray[i] == null) {
bookArray[i] = new books(name, author, category, isbn,
cost, sRating);
} else if (i == (bookArray.length - 1)) {
bookArrayAlt = new books[bookArray.length + 1];
System.arraycopy(bookArray, 0, bookArrayAlt, 0,
bookArray.length + 1);
bookArrayAlt[bookArray.length] = new books(name, author,
category, isbn, cost, sRating);
firstArrayBook = false;
}
}
}
else if (firstArrayBook == false) {
for (int i = 0; i < bookArrayAlt.length; i++) {
if (bookArrayAlt[i] == null) {
bookArrayAlt[i] = new books(name, author, category, isbn,
cost, sRating);
} else if (i == (bookArrayAlt.length - 1)) {
bookArray = new books[bookArrayAlt.length + 1];
System.arraycopy(bookArrayAlt, 0, bookArray, 0,
bookArrayAlt.length + 1);
bookArray[bookArrayAlt.length] = new books(name, author,
category, isbn, cost, sRating);
firstArrayBook = false;
}
}
}
}
public static boolean deleteStudent(String lName, int stuNum) {
students[] arrayLookedUp = lookUpLastName(lName);
boolean deleted = false;
for (int i = 0; i < arrayLookedUp.length; i++) {
if ((arrayLookedUp[i].getStuNum()) == stuNum) {
System.out.println("checker");
if (firstArrayStu == true) {
for (int j = 0; j < studentArray.length; j++) {
if (arrayLookedUp[i] == studentArray[j]) {
studentArray[j] = null;
deleted = true;
break;
}
}
break;
} else if (firstArrayStu == false) {
for (int j = 0; j < stuArrayAlt.length; j++) {
if (arrayLookedUp[i] == stuArrayAlt[j]) {
stuArrayAlt[j] = null;
deleted = true;
break;
}
}
}
} else if (i == (arrayLookedUp.length - 1)) {
deleted = false;
}
}
return deleted;
}
public static boolean checkStuNum(int stuNum) {
// private static students[] studentArray;
// private static students[] stuArrayAlt;
// private static boolean firstArrayStu=true;
boolean stuNumNew = false;
System.out.println("test");
if (firstArrayStu == true) {
for (int i = 0; i < studentArray.length; i++) {
System.out.println("false");
if ((studentArray[i].getStuNum()) == stuNum) {
System.out.println("true");
stuNumNew = true;
break;
}
}
}
else if (firstArrayStu == false) {
for (int i = 0; i < stuArrayAlt.length; i++) {
if ((stuArrayAlt[i].getStuNum()) == stuNum) {
stuNumNew = true;
break;
}
}
}
return stuNumNew;
}
}
I have a student class with a constructor, and a method that states
public String getFirstName() {
return fName;
}
but still I am getting an error. I know it is a lot of code to go through, so once again any kind of help would be greatly appreciated.
As your code is currently written,
System.out.println(studentArray[0].getFirstName());
Will throw an NPE since you're never initializing the array.
private static students[] studentArray;
Just declares it, doesn't initialize it.
Maybe you should refactor your code as follows
private static ArrayList<students> studentArray = new ArrayList<students>();
// Inside the constructor or some method called before you access studentArray:
studentArray.add(stu1);
studentArray.add(stu2);
//...
// or, more concisely, since you're not using the temporary `students` variables:
studentArray.add(new students(65435, "Bob", "Ted"));
studentArray.add(new students(45546, "Guy", "Sid"));
//...
If you're committed to using an array and not a List,
private static students[] studentArray;
needs to be initialized with something like
private static students[] studentArray = new students[10];
and then you need to assign its elements
studentArray[0] = stu1;
or
studentArray[0] = new students(65435, "Bob", "Ted");
You should always create a object before trying to access it.
You have declared a reference pointing to a array :
private static students[] studentArray;
but never assigned any object to the reference. Hence you get a NullPointerException.
Use this :
private static students[] studentArray = new students[size];
Above code will create a new object (array of students), pointed by a reference variable (studentArray).
OR
You can use List or Set which are more efficient then array.

Categories

Resources