JOptionPane input validation - java

I'm looking for a good way to check the user's input via JOptionPane showConfirmDialog, making sure it contains a string and a credible age. The idea is to use these input and add them to an object, that then gets added to an ArrayList.
The problem is in the "NyLis" class below".
Name = Namn, and Land = country. Ålder = age. Age should be between 18 and 100.
Is there a way to check that the string is an actual string?
is there a way to return the window if input is invalid, and keep the previous input, so the use can pick up where it went wrong?
Are try and catch blocks a good option here, and how would I implement them?
I've been playing around with while loops and try catch block, but I can't wrap my silly head around it all.
Any help is immensely appreciated.
// JOptionPane window
Form(){
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel rad0 = new JPanel();
rad0.add(new JLabel("StartNr: "+ list.size()+1+""));
add(rad0);
JPanel rad1 = new JPanel();
rad1.add(new JLabel("Namn: "));
namnFält = new JTextField(15);
rad1.add(namnFält);
add(rad1);
JPanel rad2 = new JPanel();
rad2.add(new JLabel("Land: "));
landFält = new JTextField(15);
rad2.add(landFält);
add(rad2);
JPanel rad3 = new JPanel();
ålderFält = new JTextField(5);
rad3.add(ålderFält);
rad3.add(new JLabel("Ålder: "));
rad3.add(ålderFält);
add(rad3);
}
}
// Listener
class NyLis implements ActionListener{
public void actionPerformed(ActionEvent ave){
Form f = new Form();
int svar = JOptionPane.showConfirmDialog(null, f);
if (svar != JOptionPane.OK_OPTION)
return;
String namn = f.namnFält.getText();
String land = f.landFält.getText();
int ålder = Integer.parseInt(f.ålderFält.getText());
boolean success=false;
while(!success){
JOptionPane.showMessageDialog(null, "Fel. Försök igen.");
int svar2 = JOptionPane.showConfirmDialog(null, f);
if (svar2 != JOptionPane.OK_OPTION)
return;
if(!namn.isEmpty() && !land.isEmpty()&&!(ålder<18 || ålder>100)){
success=true;
int startNr = list.size()+1;
Tävlande tv = new Tävlande (namn,land,ålder,startNr,Double.MAX_VALUE);
list.add(tv);
visa.setEnabled(true);
}
}
}
}
// Object
public class Tävlande implements Comparable<Tävlande>{
private String namn;
private String land;
private int ålder;
private int startNr;
private double tid;
public Tävlande (String namn, String land,int ålder,int startNr, double tid){
this.namn = namn;
this.land = land;
this.ålder = ålder;
this.startNr = startNr;
this.tid = tid;
}
public String getNamn(){
return namn;
}
public String getLand(){
return land;
}
public int getÅlder(){
return ålder;
}
public int getStartNr(){
return startNr;
}
public double getTid(){
return tid;
}
public void setTid(Double tid) {
this.tid = tid;
}
public String toString(){
String str = namn +" " + ", Land: "+land + ", Ålder: " +ålder+ ", Startnummer: " + " "+startNr;
return str;
}
public String toString2(){
String str = namn +" " + ", Land: "+land + ", Ålder: " +ålder+ ", Startnummer: " + " "+startNr+ ", Tid: "+tid;
return str;
}
public boolean equals(Object other){
if (other instanceof Tävlande){
Tävlande t = (Tävlande) other;
if (startNr == t.startNr)
return true;
else
return false;
}
else{
return false;
}
}
#Override
public int compareTo(Tävlande other) {
if(startNr < other.startNr)
return -1;
else if (startNr > other.startNr)
return 1;
else
return 0;
}
}

SpinnerNumberModel ageModel = new SpinnerNumberModel(25, 18, 100, 1);
JSpinner ageSpinner = new JSpinner(ageModel);
JOptionPane.showMessageDialog(
frame, ageSpinner, "Age?", JOptionPane.QUESTION_MESSAGE);
System.out.println(ageSpinner.getValue());

Well there is several ways you could go about doing it. For the date you could try using some methods like String Split to break up the dates by '/' and see if the dates are within a relevant range.
String string = "4/10/2014";
String[] parts = string.split("/");
String part1 = parts[0]; // 4
String part2 = parts[1]; // 10
String part3 = parts[2]; // 2014
Then do a while loop and loop the user back to the beginning for new input if the values aren't Int's or are to high or low.
Heres a link from a previous question about Int verification: Link!

Related

how to read data from arraylist that is inside linkedlist

I have an arraylist of year and value. this arraylist is place in a linkedlist as one of element in the linkedlist.
linkedlist elements -> countrycode, indicatorName, indicatorCode and data (arraylist)
how can i retrieve the value from the arraylist when i search for the indicator code and then the year?
segments of my code from application class:
while(str2 != null ){
StringTokenizer st = new StringTokenizer(str2,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct1 = new Indicator (cCode,iName,iCode,data);
bigdata.insertAtBack(idct1);
str2 = br2.readLine();
}
//search
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(bigdata,search3);
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
public static void searchYear (myLinkedList bigdata, int searchTerm) {
Indicator idct4 = (Indicator)bigdata.getFirst();
boolean found = false;
while(idct4 != null){
if(idct4.getDYear() == searchTerm) {
found = true;
System.out.println(idct4.getDValue());
}
idct4 = (Indicator)bigdata.getNext();
}
if (!found){
String message = "Error!";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",JOptionPane.ERROR_MESSAGE);
}
}
indicator class:
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
public String getCCode(){return cCode;}
public String getIName(){return iName;}
public String getICode(){return iCode;}
public int getDYear(){return d.getYear();}
public String getDValue(){return d.getValue();}
public void setCCode(String cCode){this.cCode = cCode;}
public void setIName(String iName){this.iName = iName;}
public void setICode(String iCode){this.iCode = iCode;}
public String toString(){
return (cCode + "\t" + iName + "\t" + iCode + "\t" + DataList.toString());
}
}
MyData class:
public MyData(int year, String value){
this.year = year;
this.value = value;
}
public int getYear(){return year;}
public String getValue(){return value;}
public void setYear(int year){this.year = year;}
public void setValue(String value){this.value = value;}
public String toString(){
return (value + "(" + year + ")");
}
I can't add a comment yet, but here's what I'm assuming.
Here it's getting a matching Indicator code (iCode), so let's pass the Indicator object (idct3) into searchYear method instead to focus on its ArrayList < MyData > DataList:
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(idct3,search3); // Indicator passed in here
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
Let's change searchYear method to take the Indicator class and search its DataList:
public static void searchYear (Indicator indicator, int searchTerm) {
for (int i = 0; i < indicator.DataList.size(); i++) {
if (indicator.DataList.get(i).getYear() == searchTerm) { // Sequentially get MyData object from DataList and its year for comparison
System.out.println("Found year " + searchTerm + " with Indicator code " + indicator.getICode() + " having value " + indicator.DataList.get(i).getValue());
return; // Exit this method
}
}
System.out.println("Not Found");
}

Java - changing data fields?

There are two things I need help with but I'm having a hard time figuring out. They are listed below - any assistance is greatly appreciated.
1) I need to add a method that prompts the user to enter an int (1-3) to change the volume (default set to 2). I'm really having trouble figuring out how to make this work.
2) I need to add a similar method that prompts the user to enter an int (1 or 2) to plug the head phones in.
Here's my code; one is the test class:
//Open Package
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
// Creat class for headphones
public class HeadPhone_WK6 {
//Call scanner
Scanner stdin = new Scanner(System.in);
//Initialize input variable
int Input;
//Declare constant Variables
public static final int LOW = 1;
public static final int MEDIUM = 2;
public static final int HIGH = 3;
//Declare Private variables
private int volume;
private boolean pluggedIn;
private String manufacturer;
private String headPhoneColor;
//Declare Strings
String pluggedInStat;
String volumeNow;
// Constructor for class
public HeadPhone_WK6(int volume, boolean pluggedIn, String manufacturer, String headPhoneColor) {
this.volume = volume;
this.pluggedIn = pluggedIn;
this.manufacturer = manufacturer;
this.headPhoneColor = headPhoneColor;
}
// Default Constructor for default settings
public HeadPhone_WK6() {
volume = MEDIUM;
pluggedIn = false;
manufacturer = "";
headPhoneColor = "";
}
// setVolume
public void setVolume(int volume) {
this.volume = volume;
}
// getVolume
public int getVolume() {
if (volume == 1) {
volumeNow = "LOW";
}
else if (volume == 2) {
volumeNow = "MEDIUM";
}
else {
volumeNow = "HIGH";
}
return volume;
}
// setPluggedIn
public void setPluggedIn(boolean pluggedIn) {
this.pluggedIn = pluggedIn;
}
// getPluggedIn
public boolean getPluggedIn() {
if(pluggedIn == true) {
pluggedInStat = "Plugged In";
}
else {
pluggedInStat = "Not Plugged In";
}
return pluggedIn;
}
// setManufacturer
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
// getManufacturer
public String getManufacturer() {
return manufacturer;
}
// setHeadPhoneColor
public void setHeadPhoneColor(String headPhoneColor) {
this.headPhoneColor = headPhoneColor;
}
// getHeadPhoneColor
public String getHeadPhoneColor() {
return headPhoneColor;
}
// method to create string
public String toString() {
boolean phonesPluggedIn = this.getPluggedIn();
String phoneManufacturer = this.getManufacturer();
String phoneColor = this.getHeadPhoneColor();
String currentVolume = this.volumeNow;
//Build String for characteristics of phones
StringBuilder characteristics = new StringBuilder();
characteristics.append(String.format("\nThe Head Phone Manufacturer "
+ "is: %s", phoneManufacturer));
characteristics.append(String.format("\nThe Color of the Head Phone Set "
+ "is: %s", phoneColor));
characteristics.append(String.format("\nThe Head Phones are Currently: "
+ " %s", phonesPluggedIn));
characteristics.append(String.format("\nThe Head Phone Volume is "
+ "Currently Set on: %s", currentVolume));
//return string for characteristics
return characteristics.toString();
}
}
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
//Test class for head phone
public class HeadPhone_WK6_Test {
//Command line arguments
public static void main(String[] args) {
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(2, false, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(2, false, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(2, false, "RCA", "ORANGE");
int bestPairVolume = bestPair.getVolume();
boolean bestPairPluggedIn = bestPair.getPluggedIn();
String bestPairManufacturer = bestPair.getManufacturer();
String bestPairHeadPhoneColor = bestPair.getHeadPhoneColor();
String bestPairVolumeNow = bestPair.volumeNow;
String bestPairPluggedInStat = bestPair.pluggedInStat;
int worstPairVolume = worstPair.getVolume();
boolean worstPairPluggedIn = worstPair.getPluggedIn();
String worstPairManufacturer = worstPair.getManufacturer();
String worstPairHeadPhoneColor = worstPair.getHeadPhoneColor();
String worstPairVolumeNow = worstPair.volumeNow;
String worstPairPluggedInStat = worstPair.pluggedInStat;
int decentPairVolume = decentPair.getVolume();
boolean decentPairPluggedIn = decentPair.getPluggedIn();
String decentPairManufacturer = decentPair.getManufacturer();
String decentPairHeadPhoneColor = decentPair.getHeadPhoneColor();
String decentPairVolumeNow = decentPair.volumeNow;
String decentPairPluggedInStat = decentPair.pluggedInStat;
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
//Loop for random headphone selection
if (Input == 1){
//echo user input
System.out.println("You have chosen the best pair of "
+ "headphones! Here is a list of the characteristics: ");
System.out.println(bestPair.toString());
//End if
}
else if (Input == 2){
System.out.println("You have chosen the worst pair of "
+ "headphones. Here is a list of the characteristics: ");
System.out.println(worstPair.toString());
//End If
}
else if(Input == 3){
System.out.println("You have chosen a decent pair of "
+ "headphones. Here is a list of the characteristics:");
System.out.println(decentPair.toString());
//End If
}
else{
System.out.println("You have expressed that you want to see "
+ "the default pair of headphones. They are the "
+ "decent pair! Here's a list of the characteristics:");
System.out.println(decentPair.toString());
}
}
}
Maybe try something like this, first get input via scanner, then create HeadPhone objects:
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
boolean pluggedIn=true;
if(plugInState==1) pluggedIn = false;
if(plugInState==2) pluggedIn = true;
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
HeadPhone_WK6 bestPair = new HeadPhone_WK6(volumeState, pluggedIn, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(volumeState, pluggedIn, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(volumeState, pluggedIn, "RCA", "ORANGE");
You can put if clause in the end, based on your input, you can create one object that you need. If you need separate methods, do this in main():
HeadPhone_WK6 hp = new HeadPhone_WK6();
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
hp.setPluggedIn(plugInState);
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
hp.setVolume(volumeState);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "RCA", "ORANGE");
Where
setPluggedIn(int pluggedInState) {
if(plugInState==1) pluggedIn = false;
else if(plugInState==2) pluggedIn = true;
else {
pluggedIn = false;
}
}

NullPointerException when attempting to insert items into array from JDialog box

As it states, when I attempt to insert an item into an object array via my JDialog popup, I get a NullPointerException. I reworked an existing app to create the JDialog, which opens from another application class currently named Project6(). The JDialog class, called ProcessRec(), worked fine when it ran as a standalone GUI(before I made it a JDialog).
My stacktrace is rather unhelpful in this case, as it only points to the method that is attempting to insert data into the array(which, like I said, worked fine before) and the GUI buttons that correspond to them.
The constructor for ProcessRec() accepts a ToolWarehouse() object, which matches the class that creates my object array(which is an array of objects from another class I have defined, ToolItem() ).
public ProcessRec(ToolWarehouse tools)
When it ran on it's own, ProcessRec() constructor params were empty(default).
When ProcessRec() ran as a standalone GUI for inputting data into the array, I would create an object using the default constructor like so:
ToolWareHouse tools = new ToolWarehouse();
and I would then use it's method insert() to enter data into the array.
Now that it is a JDialog, though, I was instructed to change to:
ToolWarehouse tools;
However this causes the NullPointerException because, and i'm guessing, the compiler is pointing to an object that doesn't exist. When I create a new object in ProcessRec(), as I did when it was a standalone, I no longer get this exception. However, when I attempt to store data into the array using insert(), it does not work and the data cannot be found(although I receive a prompt saying the insert was successful).
I know very little about instances of classes, but i'm assuming that the reason my data isn't showing is because it is using a whole different instance of the ToolWarehouse() class? Is the format:
public ProcessRec(ToolWarehouse tools)
accepting the same instance of the class used before? I may be way off base here, so I was hoping someone could help me understand what may be happening and why.
If more info is needed I apologize, i'll add whatever is necessary. The code is somewhat lengthy and I didn't want to take up space. Thanks a ton.
EDIT: Here is the ProcessRec() class, which creates the JDialog box, along with some of the methods corresponding to it's use.
public class ProcessRec extends JDialog
{
//global declarations
private JButton insertBtn;
private JButton deleteBtn;
private JButton displayBtn;
private JButton hideBtn;
private JButton clearBtn;
private JTextField toolFld;
private JTextField idFld;
private JTextField priceFld;
private JTextField qualityFld;
private JTextField numInStockFld;
private JTextField messageFld;
private JLabel messageLbl;
private Font f1 = new Font("serif", Font.BOLD, 24);
private Font f2 = new Font("serif", Font.PLAIN, 18);
private Container c = getContentPane();
private String input = "";
private String toolInput = "";
private int responseCode = 0;
private int idInput = 0;
private int qualityInput = 0;
private int numInStockInput = 0;
private double priceInput = 0.0;
private ToolWarehouse tools = new ToolWarehouse();
//constructor for GUI elements and event listeners
public ProcessRec(ToolWarehouse tools)
{
setTitle("Project1");
setSize(520,450);
c.setLayout(new FlowLayout());
JLabel title = new JLabel("Tiny Tim's Tool Warehouse, Inc.");
title.setFont(f1);
c.add(title);
JTextField toolLbl = new JTextField("Enter tool name:", 15);
toolLbl.setEditable(false);
c.add(toolLbl);
toolFld = new JTextField(25);
c.add(toolFld);
JTextField idLbl = new JTextField("Enter ID:", 15);
idLbl.setEditable(false);
c.add(idLbl);
idFld = new JTextField(25);
c.add(idFld);
JTextField priceLbl = new JTextField("Base Price:", 15);
priceLbl.setEditable(false);
c.add(priceLbl);
priceFld = new JTextField(25);
c.add(priceFld);
JTextField qualityLbl = new JTextField("Enter Quality:", 15);
qualityLbl.setEditable(false);
c.add(qualityLbl);
qualityFld = new JTextField(25);
c.add(qualityFld);
JTextField numInStockLbl = new JTextField("Enter Number in Stock:", 15);
numInStockLbl.setEditable(false);
c.add(numInStockLbl);
numInStockFld = new JTextField(25);
c.add(numInStockFld);
insertBtn = new JButton("Insert");
c.add(insertBtn);
deleteBtn = new JButton("Delete");
c.add(deleteBtn);
displayBtn = new JButton("Display");
c.add(displayBtn);
hideBtn = new JButton("Hide");
c.add(hideBtn);
clearBtn = new JButton("Clear");
c.add(clearBtn);
JLabel messageLbl = new JLabel("Messages:");
messageLbl.setFont(f2);
c.add(messageLbl);
messageFld = new JTextField(30);
c.add(messageFld);
//button listeners
insertBtn.addActionListener(new EventListener());
deleteBtn.addActionListener(new EventListener());
displayBtn.addActionListener(new EventListener());
hideBtn.addActionListener(new EventListener());
clearBtn.addActionListener(new EventListener());
} //end constructor
public String getToolRecords(int index)
{
return tools.getRecord(index);
}
public int getNumberOfItems()
{
return tools.getNumberOfItems();
}
//Action Listener
private class EventListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
if (ev.getSource() == insertBtn)
{
toolInput = toolFld.getText();
input = idFld.getText();
idInput = Integer.parseInt(input);
input = priceFld.getText();
priceInput = Double.parseDouble(input);
input = qualityFld.getText();
qualityInput = Integer.parseInt(input);
input = numInStockFld.getText();
numInStockInput = Integer.parseInt(input);
responseCode = tools.insert(qualityInput, toolInput, idInput, numInStockInput,
priceInput);
if (responseCode == 1)
{
messageFld.setText(idInput + " - Successful insertion");
}
else if (responseCode == 0)
{
messageFld.setText(idInput + " - Array is full");
}
else if (responseCode == -1)
{
messageFld.setText(idInput + " - Duplicate/Invalid ID");
}
if (tools.getNumberOfItems() < 10)
{
JOptionPane.showMessageDialog(null, "Tool Name: " + toolInput
+ "\nTool ID: " + idInput + "\nTool Base Price: " + "$" + priceInput
+ "\nQuality: " + qualityInput + "\nNumber In Stock: "
+ numInStockInput, "Insert Review", JOptionPane.INFORMATION_MESSAGE);
}
else if (tools.getNumberOfItems() == 10)
{
JOptionPane.showMessageDialog(null, "The array is full, please delete an entry",
"Insert Review", JOptionPane.INFORMATION_MESSAGE);
}
}//end insert button
else if (ev.getSource() == deleteBtn)
{
input = idFld.getText();
idInput = Integer.parseInt(input);
responseCode = tools.delete(idInput);
if (responseCode == 1)
{
messageFld.setText(idInput + " - Successful deletion");
}
else if (responseCode == -1)
{
messageFld.setText(idInput + " - ID not found");
}
}//end delete button
else if (ev.getSource() == displayBtn)
{
tools.display();
}
else if (ev.getSource() == hideBtn)
{
//setState(JFrame.ICONIFIED);
}
else if (ev.getSource() == clearBtn)
{
qualityFld.setText(null);
toolFld.setText(null);
idFld.setText(null);
numInStockFld.setText(null);
priceFld.setText(null);
messageFld.setText(null);
repaint();
}//end clear button
}//end actionPerformed
}//end ActionListener
}//end Project1
ToolWarehouse class that creates the array:
public class ToolWarehouse
{
//Global declarations
private int numberOfItems = 0;
private int index = 0;
private int returnCode = 0;
protected ToolItem[] toolArray = new ToolItem[10];
public ToolWarehouse()
{
numberOfItems = 0;
//creating the array of ToolItems
for (int i = 0; i < toolArray.length; i++)
{
toolArray[i] = new ToolItem();
System.out.println(toolArray[i]);
}
}//end constructor
public int searchArray(int id)
{
for (index = 0; index < toolArray.length; index++)
{
if (toolArray[index].getToolID() == id)
{
System.out.println("ID found at location " + index);
return index;
}
}
return -1;
}//end searchArray
public int insert(int quality, String name, int id, int numInStock, double price)
{
returnCode = searchArray(id);
if (numberOfItems == 10)
{
System.out.println("Array is full");
return 0;
}
else if (returnCode == -1)
{
boolean oK = toolArray[numberOfItems].assign(quality, name, id, numInStock,
price);
if (oK == true)
{
System.out.println("Successful insertion");
numberOfItems++;
return 1;
}
}
return -1;
}//end insert
public int delete(int ID)
{
returnCode = searchArray(ID);
if (returnCode != -1)
{
toolArray[returnCode] = new ToolItem();
for (index = returnCode; index < numberOfItems; index++)
{
toolArray[index] = toolArray[index + 1];
}
numberOfItems--;
System.out.println("Successful deletion");
return 1;
}
else
System.out.println("ID not found");
return -1;
}//end delete
public void display()
{
for (index = 0; index < numberOfItems; index++)
{
toolArray[index].calcAdjustedPrice();
toolArray[index].display();
}
}//end display
public String getRecord(int index)
{
return "Tool Name: " + toolArray[index].getName()
+ "| Tool ID: " + toolArray[index].getToolID()
+ "| Tool Quality: " + toolArray[index].getQuality()
+ "| Number in Stock: " + toolArray[index].getNumberInStock()
+ "| Tool Price: " + toolArray[index].getPrice();
}//end getRecord
public int getNumberOfItems()
{
return numberOfItems;
}
}//end ToolWarehouse
And the current portion i'm working on now, which calls insert() from the ToolWarehouse() class, but does not properly insert into the array i'm working on when creating an object of the ToolWarehouse() class using default constructor(even though my println debugging statements indicate it does):
public void readBSAFile() throws IOException,
FileNotFoundException
{
FileInputStream fstream2 = new FileInputStream(filename);
DataInputStream dstream2 = new DataInputStream(fstream2);
while (dstream2.available() > 0)
{
try
{
toolName = dstream2.readUTF();
id = dstream2.readInt();
quality = dstream2.readInt();
numInStock = dstream2.readInt();
price = dstream2.readDouble();
dstream2.close();
System.out.println(toolName);
System.out.println(id);
System.out.println(quality);
System.out.println(numInStock);
System.out.println(price);
//tools.insert(quality, toolName, id, numInStock, price);
}
catch (EOFException e)
{
System.out.println("End of file reached");
}
}
tools.insert(quality, toolName, id, numInStock, price);
}//end readBSAFile
Indeed, you have to make sure the object is initialized before attempting to use it. You put
ToolWarehouse tools;
as a class variable, and in the dialog method you could say
tools = new ToolWareHouse();
to create the object and start using it. But maybe a better way is to just initialize it as a class variable straight way. e.g write
ToolWarehouse tools = new ToolWareHouse();
at the top of the class. (So it's a class variable, and known throughout the whole class)
You didn't show us too much code, so it's hard to tell what the exact problem is. But as you said, you don't initialize your object, so you're bound to get a nullPointerException when trying to pass it on to another method & use it.

How do I store objects created into an ArrayList and return it?

I'm asked to create a method called listOfWorkers in which i will create objects of each type of the 3 workers I have by reading the data from the file "workers.txt" and then store the objects into an ArrayList of type Worker and return it. I have managed to make the objects of each type of the 3 workers with by reading the data from the file, but now I don't know how to store them into an ArrayList. Any help guys?
Class i'm coding in right now
import java.util.*;
import java.io.*;
public class WorkerBenefits
{
public ArrayList<Worker> listOfWorkers()
{
try
{
File ifile = new File("worker.txt");
Scanner scan = new Scanner(ifile);
while (scan.hasNextLine())
{
String line = scan.nextLine();
StringTokenizer st = new StringTokenizer(line,",");
String jobs = st.nextToken();
Jobs jobType = Jobs.valueOf(jobs);
//Engineer Object type
if (jobType == Jobs.ELECTRICAL_ENGINEER || jobType == Jobs.MECHANICAL_ENGINEER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
Engineer eng = new Engineer(name,social,years,jobType,weeklyBen);
}
//Admin. Person. Object type
else if (jobType == Jobs.ADMINISTRATIVE_SECRETARY || jobType == Jobs.ADMINISTRATIVE_ASSISTANT)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double rate = Double.parseDouble(str3);
String str4 = st.nextToken();
double hours = Double.parseDouble(str4);
AdministrativePersonnel ap = new AdministrativePersonnel(name,social,years,jobType,rate,hours);
}
//Management Object type
else if (jobType == Jobs.ENGINEERING_MANAGER || jobType == Jobs.ADMINISTRATIVE_MANAGER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
String str4 = st.nextToken();
double bonus = Double.parseDouble(str4);
Management mang = new Management(name,social,years,jobType,weeklyBen,bonus);
}
}
}
catch (IOException ioe)
{
System.out.println("Something went wrong");
}
return ArrayList;
}
}
Here is the code for the other classes just in case you guys need them:
Jobs
public enum Jobs {ELECTRICAL_ENGINEER, MECHANICAL_ENGINEER, ADMINISTRATIVE_SECRETARY, ADMINISTRATIVE_ASSISTANT, ENGINEERING_MANAGER, ADMINISTRATIVE_MANAGER, NONE};
Worker
public abstract class Worker
{
public String name;
public int socialSecurity;
private int yearsExperience;
public Jobs et = null;
public static int id = 0;
public int currentID = 0;
public Worker ()
{
name = "AnyName";
socialSecurity = 12345;
yearsExperience = 0;
et = Jobs.NONE;
id++;
currentID = id;
}
public Worker (String n, int ss, int ye, Jobs j)
{
id++;
currentID = id;
name = n;
socialSecurity = ss;
yearsExperience = ye;
et = j;
}
public String getName()
{
return name;
}
public int getSocialSecurity()
{
return socialSecurity;
}
public int getYearsExperience()
{
return yearsExperience;
}
public Jobs getJobs()
{
return et;
}
public void setName(String n1)
{
name = n1;
}
public void setSocialSecurity(int ss1)
{
socialSecurity = ss1;
}
public void setYearsExperience(int ye1)
{
yearsExperience = ye1;
}
public void setJobs(Jobs et1)
{
et = et1;
}
public abstract double benefitsCalculation(Jobs et2);
public String toString()
{
String output = "The name is: " + name + "The Job type is: " + et + "The id is: " + currentID;
return output;
}
}
Engineer
public class Engineer extends Worker
{
private double weeklyBenefits;
public Engineer ()
{
super();
weeklyBenefits = 400.00;
}
public Engineer (String n, int ss, int ye, Jobs j, double wb)
{
super(n,ss,ye,j);
weeklyBenefits = wb;
super.setName(n);
super.setSocialSecurity(ss);
super.setYearsExperience(ye);
super.setJobs(j);
}
public double benefitsCalculation(Jobs et2)
{
double benefits = 0.0;
if (et2 == Jobs.ELECTRICAL_ENGINEER)
{
benefits = weeklyBenefits+super.getYearsExperience()*120.00;
}
else if (et2 == Jobs.MECHANICAL_ENGINEER)
{
benefits = weeklyBenefits/2+super.getYearsExperience()*120.00;
}
else if (et2 != Jobs.ELECTRICAL_ENGINEER || et2 != Jobs.MECHANICAL_ENGINEER)
{
benefits = 0;
}
return benefits;
}
public double getWeeklyBenefits()
{
return weeklyBenefits;
}
public void setWeeklyBenefits(double wb)
{
weeklyBenefits = wb;
}
public String toString()
{
String output = "The benefit is " + weeklyBenefits + super.toString();
return output;
}
}
Administrative Personnel
public class AdministrativePersonnel extends Worker
{
private double rate;
private double hours;
public AdministrativePersonnel()
{
super();
rate = 10.0;
hours = 10.0;
}
public AdministrativePersonnel(String n, int ss, int ye, Jobs j, double r, double h)
{
super(n,ss,ye,j);
rate = r;
hours = h;
super.setName(n);
super.setSocialSecurity(ss);
super.setYearsExperience(ye);
super.setJobs(j);
}
public double benefitsCalculation (Jobs et2)
{
double benefits = 0.0;
if (et2 == Jobs.ADMINISTRATIVE_SECRETARY)
{
benefits = rate*hours+super.getYearsExperience()*15.00;
}
else if(et2 == Jobs.ADMINISTRATIVE_ASSISTANT)
{
benefits = rate*hours+super.getYearsExperience()*25.00;
}
else if (et2 != Jobs.ADMINISTRATIVE_SECRETARY || et2 != Jobs.ADMINISTRATIVE_ASSISTANT)
{
benefits = 0;
}
return benefits;
}
public double getRate()
{
return rate;
}
public double getHours()
{
return hours;
}
public void setRate(double r1)
{
rate = r1;
}
public void setHours(double h1)
{
hours = h1;
}
public String toString()
{
String output = "The rate is: " + rate + "The hours are: " + hours + super.toString();
return output;
}
}
Management
public class Management extends Worker
{
private double weeklyBenefits;
private double bonus;
public Management()
{
super();
weeklyBenefits = 0.0;
bonus = 0.0;
}
public Management(String n, int ss, int ye, Jobs j, double wb, double b)
{
super(n,ss,ye,j);
weeklyBenefits = wb;
bonus = b;
super.setName(n);
super.setSocialSecurity(ss);
super.setYearsExperience(ye);
super.setJobs(j);
}
public double benefitsCalculation (Jobs et2)
{
double benefits = 0.0;
if (et2 == Jobs.ENGINEERING_MANAGER)
{
benefits = weeklyBenefits+bonus;
}
else if(et2 == Jobs.ADMINISTRATIVE_MANAGER)
{
benefits = weeklyBenefits+0.5*bonus;
}
else if (et2 != Jobs.ENGINEERING_MANAGER || et2 != Jobs.ADMINISTRATIVE_MANAGER)
{
benefits = 0;
}
return benefits;
}
public double getWeeklyBenefits()
{
return weeklyBenefits;
}
public double getBonus()
{
return bonus;
}
public void setWeeklyBenefits(double wb)
{
weeklyBenefits = wb;
}
public void setBonus(double b)
{
bonus = b;
}
public String toString()
{
String output = "The weekly benefits are: " + weeklyBenefits + "The bonus is: " + bonus + super.toString();
return output;
}
}
public ArrayList<Worker> listOfWorkers()
{
List<Worker> list=new ArrayList<Worker>();
try
{
File ifile = new File("worker.txt");
Scanner scan = new Scanner(ifile);
while (scan.hasNextLine())
{
// no change
if (jobType == Jobs.ELECTRICAL_ENGINEER || jobType == Jobs.MECHANICAL_ENGINEER)
{
// no change
Worker eng = new Engineer(name,social,years,jobType,weeklyBen);
list.add(eng);
}
else if()
{
//do same as above for other workers
}
}
return list;
}
The listOfWorkers() methods would need to create a list of workers, add each of the new worker object then return the list.
public List<Worker> listOfWorkers()
{
List<Worker> workers = new ArrayList<Worker>();
try
{
File ifile = new File("worker.txt");
Scanner scan = new Scanner(ifile);
while (scan.hasNextLine())
{
String line = scan.nextLine();
StringTokenizer st = new StringTokenizer(line,",");
String jobs = st.nextToken();
Jobs jobType = Jobs.valueOf(jobs);
//Engineer Object type
if (jobType == Jobs.ELECTRICAL_ENGINEER || jobType == Jobs.MECHANICAL_ENGINEER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
Engineer eng = new Engineer(name,social,years,jobType,weeklyBen);
workers.add(eng);
}
//Admin. Person. Object type
else if (jobType == Jobs.ADMINISTRATIVE_SECRETARY || jobType == Jobs.ADMINISTRATIVE_ASSISTANT)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double rate = Double.parseDouble(str3);
String str4 = st.nextToken();
double hours = Double.parseDouble(str4);
AdministrativePersonnel ap = new AdministrativePersonnel(name,social,years,jobType,rate,hours);
workers.add(ap);
}
//Management Object type
else if (jobType == Jobs.ENGINEERING_MANAGER || jobType == Jobs.ADMINISTRATIVE_MANAGER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
String str4 = st.nextToken();
double bonus = Double.parseDouble(str4);
Management mang = new Management(name,social,years,jobType,weeklyBen,bonus);
workers.add(mang);
}
}
}
catch (IOException ioe)
{
System.out.println("Something went wrong");
}
return workers;
}
Before the try block, create a new ArrayList of worker objects:
ArrayList<Worker> workerList = new ArrayList<Worker>();
At the beginning of the while loop, declare a new worker variable but don't create it yet:
Worker worker = null;
Within each if block, assign the result to worker rather than assigning it to a new variable of type Engineer, Management, or AdministrativePersonnel. For example, replace this:
Engineer eng = new Engineer(name,social,years,jobType,weeklyBen);
with this:
worker = new Engineer(name,social,years,jobType,weeklyBen);
This is legal because Engineer, Management, and AdministrativePersonnel are all subclasses of Worker.
Just before the end of the while loop, add your new worker to the list:
workerList.add(worker);
Finally, return workerList from the function.

Null Pointer Exception Java Card Game War

I'm trying to making a program that simulates the card game War.
class Project2
package proj2;
import java.util.Scanner;
public class Project2 {
public static void main( String[ ] args)
{
Scanner keybd = new Scanner( System.in );
// Get player names
System.out.println("Welcome to WAR!!");
System.out.print("Please enter player 1's name: ");
String p1Name = keybd.nextLine();
System.out.print("Please enter player 2's name: ");
String p2Name = keybd.nextLine();
// Get random number generator (RNG) seed and initialize the game
System.out.print ("Please enter the RNG seed for shuffling: ");
long rngSeed = keybd.nextLong();
Game war = new Game(p1Name, p2Name, rngSeed);
int turn = 1;
// While game is being played, print details and results of each turn
while (!war.gameComplete())
{
System.out.printf( "Turn %2d\n", turn);
System.out.println( "-----");
System.out.println( war.nextTurn());
++turn;
}
// All turns complete; print the game results
System.out.println("Game Over!!");
System.out.println(war.gameResult());
}
}
Class Game:
package proj2;
public class Game {
private Deck deck;
private Player player1;
private CardPile p1Deck;
private Player player2;
private CardPile p2Deck;
private int warCount;
private int turns;
public Game(String p1, String p2, long rngSeed)
{
this.deck = new Deck();
deck.Shuffle((int) rngSeed);
this.player1 = new Player(p1, 0, 0);
this.p1Deck = new CardPile(deck.Deal());
this.player2 = new Player(p2, 0, 0);
this.p2Deck = new CardPile(deck.Deal());
this.turns = 1;
this.warCount = 0;
}
public String nextTurn()
{
p1Card = p1Deck.drawCard();
(ERROR)---> String p1Turn = player1.getName() + " shows " + p1Card.cardString();
Card p2Card = p2Deck.drawCard();
String p2Turn = player2.getName() + " shows " + p2Card.cardString();
String winner = "";
if(p1Card.getValue() > p2Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p1Card;
wonCards[1] = p2Card;
p1Deck.addCard(wonCards, 2);
player1.setCardsWon(wonCards.length);
winner = player1.getName() + " wins 2 cards" ;
}
if(p2Card.getValue() > p1Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p2Card;
wonCards[1] = p1Card;
p1Deck.addCard(wonCards, 2);
player2.setCardsWon(wonCards.length);
winner = "/n" + player2.getName() + " wins 2 cards";
}
String warTurn = "";
if(p1Card.getValue() == p2Card.getValue())
{
this.warCount = warCount + 1;
warTurn = "WAR!!";
Card[] wonCards = new Card[8];
while(p1Card.getValue() != p2Card.getValue())
{
wonCards[0] = p1Deck.drawCard();
wonCards[2] = p1Deck.drawCard();
wonCards[4] = p1Deck.drawCard();
Card p1WarCard = p1Deck.drawCard();
wonCards[6] = p1WarCard;
wonCards[1] = p2Deck.drawCard();
wonCards[3] = p2Deck.drawCard();
wonCards[5] = p2Deck.drawCard();
Card p2WarCard = p2Deck.drawCard();
wonCards[7] = p2WarCard;
if(p1WarCard.getValue() > p2WarCard.getValue())
{
p1Deck.addCard(wonCards, wonCards.length);
player1.setCardsWon(wonCards.length);
}
if(p2WarCard.getValue() > p2WarCard.getValue())
{
p2Deck.addCard(wonCards, wonCards.length);
player2.setCardsWon(wonCards.length);
}
}
}
String turnResults = p1Turn + "/n" + p2Turn + "/n" + warTurn + winner;
return turnResults;
}
public boolean gameComplete()
{
boolean result = false;
if(turns == 20) {
result = true;
}
return result;
}
public String gameResult()
{
String p1Result = (player1.getName() + " won " + player1.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String p2Result = (player2.getName() + " won " + player2.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String winner = "";
if(player1.getCardsWon() > player2.getCardsWon())
{
winner = "Winner: " + player1.getName();
}
if(player2.getCardsWon() < player2.getCardsWon())
{
winner = "Winner: " + player2.getName();
}
if(player1.getCardsWon() == player2.getCardsWon())
{
winner = "Game is a draw";
}
String finalResult = ("Game Over!!" + "There were " + warCount
+ "war(s)" + p1Result + "/n" + p2Result + "/n" + winner);
return finalResult;
}
}
When I try to access the class Card, I get a null pointer exception error. I'm not sure what is producing the error.
public class Card {
private char rank;
private String suit;
private int value;
public Card(char rank, String suit, int value)
{
this.rank = rank;
this.suit = suit;
this.value = value;
}
public char getRank()
{
return rank;
}
public String getSuit()
{
return suit;
}
public int getValue()
{
return value;
}
public String cardString()
{
String card = (rank + " of " + suit);
return card;
}
}
I tried googling for solutions, and it tells me to initialize the object before referencing the object. I tried initializing, but it still produces the null pointer exception error.
The error I'm getting is this.
Exception in thread "main" java.lang.NullPointerException
at proj2.Game.nextTurn(Game.java:29)
at proj2.Project2.main(Project2.java:37)
The drawCard() method is from this class.
package proj2;
public class CardPile {
private Card[] playerDeck;
public CardPile(Card[] deck)
{
this.playerDeck = deck;
}
public Card drawCard()
{
Card topCard = playerDeck[0];
Card[] newPlayerDeck = new Card[playerDeck.length - 1];
int counter = 0;
for(int i = 1; i < playerDeck.length; i++)
{
newPlayerDeck[counter] = playerDeck[i];
counter++;
}
this.playerDeck = newPlayerDeck;
return topCard;
}
}
It returns a NULL Point Exception because you are not passing any parameters. Try passing parameters to your constructor.
e.g
Card p1Card = new Card(rank,suit,value);
Card p2Card = new Card(rank,suit,value);
Since p1Card null, then p1Deck.drawCard() returns null - which means playerDeck[0] is null, which means new CardPile(deck.Deal()); creates and empty deck, which means something is wrong in deck.Deal(). By "something is wrong" I mean that it probably creates and returns an array with null values, like: [null, null, null, null, null] (or it might be that the first value is the only one that's null).

Categories