-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInventory.java
More file actions
109 lines (101 loc) · 2.78 KB
/
Inventory.java
File metadata and controls
109 lines (101 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package org.uob.a1;
public class Inventory {
//Declaring attributes
private String contents[];
final int MAX_ITEMS = 10;
//Constructor method
public Inventory()
{
this.contents = new String[MAX_ITEMS];
for (int i = 0; i < MAX_ITEMS; i++)
{
contents[i] = "empty";
}
}
//Method to add an item to the player's inventory
public void addItem(String Item)
{
//Declaring variable outside of for loop
int location = (-1);
//For loop to check the empty space for the next empty space in the array
for (int i = 0; i < MAX_ITEMS; i++)
{
if (this.contents[i] == "empty")
{
location = i;
break;
}
}
//If statement to add the item if there is space
if (location > (-1))
{
this.contents[location] = Item;
}
else
{
System.out.println("There is no space in your inventory");
}
}
//Method to determine if the player has the item in their inventory
public int hasItem(String item)
{
//Use a while loop to check if an item (parameter) is in the player's inventory
boolean found = false;
int counter = 0;
while (found == false && counter<MAX_ITEMS)
{
if (contents[counter].equals(item))
{
found = true;
}
counter++;
}
//If statement to determine the index if the object was found
if (found == false)
{
return -1;
}
else
{
return counter;
}
}
//Method to remove an item from the inventory
public void removeItem(String item)
{
//Similar process to addItem() but to remove an item from the inventory
boolean found = false;
int counter = 0;
while (found == false && counter < MAX_ITEMS)
{
if ((contents[counter]).equals(item))
{
found = true;
}
counter++;
}
if (found == true)
{
counter = counter - 1;
contents[counter] = "empty";
}
else
{
System.out.println("The item entered is not in your inventory");
}
}
//Method to return the players inventory in a string
public String displayInventory()
{
String toDisplay = "";
for (int i = 0; i < MAX_ITEMS; i++)
{
if (contents[i] != "empty")
{
//Displaying the contents of each index (inlcuding the empty slots)
toDisplay = toDisplay + contents[i] + " ";
}
}
return toDisplay;
}
}