first of all thank you for looking at my question. My assignment is pretty basic to most but I am an inexperienced programmer. Here is the description of the assignment:
Your objective is to write a class called Storage that can hold a collection of Strings. It must implement the following methods:
addItem(String s) - This method accepts a String parameter and returns a boolean value. The parameter reference is then stored internally in your choice of structure. The method returns true if the reference is successfully added.
getItems() - This method takes no parameters and returns an array containing all the Strings stored in the internal structure. The returned array must not contain any null elements.
isFull() - This method returns true if there is no internal storage available, otherwise false.
removeItem(String s) - This method accepts a String parameter and returns a boolean value. The method must search through the internal storage structure and remove the parameter reference (if present). The method returns true if the reference is successfully removed, otherwise false.
I am completely stumped on most of these. I am using an array to store the data, but I am open to other suggestions. Thanks again.
Alright guys I made a few changes and I started some code, but it won't compile correctly. Based on the description of the methods can someone tell me what I'm doing wrong?
public class Storage {
//variables
private String[] list;
private int size = 10;
private int index = 0;
public boolean addItem(String s) {
for (int i = 0; i < list.length; i++) {
if (!list.equals(null)) {
list[i] = s;
}
}
return true;
}
public String[] getItems() {
for (int i = 0; i < list.length; i++) {
if(!list.equals(null)) {
System.out.println(list[i]);
i++;
}
}
return list;
}
public boolean isFull() {
if (list.length > size) {
System.out.println("The array is full");
}
return true;
}
public boolean removeItem(String s) {
for (int i = index; i < list.length - 1; i++) {
list[i] = list[i + 1];
}
return true;
}
}
addItem(String s): The method should return a boolean value, since you are using an ArrayList, we can use add(Object o), which returns a boolean.
public boolean addItem(String s) {
return list.add(s); // I'm assuming that your instance variable is named list
}
getItems(): Use the method in the ArrayList class called toArray(), passing in an argument of the array type to cast to.
public String[] getItems() {
return list.toArray(new String[list.size()]);
}
isFull(): Not exactly sure what your instructor was asking for here, as an ArrayList will automatically resize, but you could just add an instance variable to your class that contains a maximum size and then check against it like so...
public static final int SIZE = 10;
...
public boolean isFull() {
return list.size() >= SIZE;
}
of course, this means adding code to check that the element you're adding doesn't breach capacity. I'll show this in the complete example below.
removeItem(String s): The remove() method in ArrayList is overloaded to accept an object to remove. Likewise, this method also returns a boolean value.
public boolean removeValue(String s) {
return list.remove(s); // Removes the first occurrence of the string
}
All in all, you should have something similar to the following...
public class Storage {
private ArrayList<String> list = new ArrayList<>();
public static final int SIZE = 10;
public boolean addItem(String s) {
if (isFull())
return false;
return list.add(s);
}
public String[] getItems() {
return list.toArray(new String[list.size()]);
}
public boolean isFull() {
return list.size() >= SIZE;
}
public boolean removeValue(String s) {
return list.remove(s); // Removes the first occurrence of the string
}
}
Related
I need help with creating a method that adds input int to an array, and returning a message if array is already full.
I have class Lista with 3 fields numbers, capacity and size. Than I have a counstructor taking int as parameter and seting the capacity of array for the object of Lista class. So far i have this code:
public class Lista {
private int[] numbers;
private int capacity;
private int size;
public Lista (int capacity) {
this.size = 0;
this.capacity = capacity;
this.numbers = new int[capacity];
}
public void addElement(int element) {
}
public static void main(String[] args) {
Lista lista = new Lista(10);
lista.addElement(1);
lista.addElement(2);
lista.addElement(3);
System.out.println(lista.numbers[1]);
I've tried with loops and ArrayLIst but nothing i wrotr realy worked. WHat would be the best way to do it?
You could implement your addElement method like so:
public void addElement(int element) {
if(size == capacity) {
System.out.println("array is full");
return;
}
numbers[size++] = element;
}
You need to throw exception when list is already full and you try to insert next element to it:
class List {
private int[] numbers;
private int nextIndex;
public List(int capacity) {
this.numbers = new int[capacity];
}
public void addElement(int element) {
if (nextIndex < numbers.length) {
numbers[nextIndex] = element;
nextIndex++;
} else {
throw new RuntimeException("list is full");
}
}
public int capacity() {
return numbers.length;
}
public int size() {
return nextIndex;
}
}
I've tried with loops and ArrayLIst but nothing i wrotr realy worked.
WHat would be the best way to do it?
You use an array to store your values, so you don't need to use ArrayList (it is an alternative).
A loop is for iterating. You don't need it either.
I need help with creating a method that adds input int to an array,
and returning a message if array is already full.
Returning a textual message is not really the way which an API should be designed. It should rather returns a boolean to indicate the result of the invocation.
For example, look at the boolean add(E e) method of the Collection interface.
So, you should change the declaration of addElement() in order to return a boolean to indicate if the element was added or not (the last one when the max capcacity was reached).
public boolean addElement(int element) {
if(size == capacity) {
return false;
}
numbers[size++] = element;
return true;
}
If you want to output a textual message, you could test the value of the boolean :
if (!myLista.addElement(5)){
System.out.println("max capacity added. Cannot add the element");
}
I want to get the particular index of the array list, by using only contained text. Say suppose,
I have arraylist as
Test = {"LabTechnician","SeniorLabTechnician_4","Pathologist","SeniorLabTechnician_6"}
If want the index nos of both the SeniorLabTechnician, i have to use the exact string in the indexOf and lastindexOf method. Like Test.indexOf("SeniorLabTechnician_4") and Test.lastindexOf("SeniorLabTechnician_6")
this is will get me the exact answer.. But instead of that,by using only prefix say like senior or some thing like, i want the exact same answer before..
Like
Test.indexOf("Senior") and Test.lastindexOf("Senior")...
Please suggest
Loop over the list and compare the elements with contains:
int indexOfContains(List<String> lst, String what) {
for(int i=0;i<lst.size();i++){
//this will make the check case insensitive, see JAVY's comment below:
//if(lst[i].toLowerCase().contains(what.toLowerCase())) {
if(lst[i].contains(what)){
return i;
}
}
return -1;
}
If you want something like lastIndexOf then just reverse the order in which the list is iterated.
As I understand, you want to modify default behaviour of indexOf and lastIndexOf methods of ArrayList.
My solution is create a new class CustomArrayList extends ArrayList.
Override indexOf method
Override lastIndexOf method
public class CustomArrayList extends ArrayList {
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size(); i++)
if (get(i) == null)
return i;
} else {
for (int i = 0; i < size(); i++)
if(o instanceof String) {
if(get(i).toString().startsWith(o.toString())) {
return i;
}
} else {
if (o.equals(get(i)))
return i;
}
}
return -1;
}
public static void main(String[] args) {
List list = new CustomArrayList();
list.add("LabTechnician");
list.add("SeniorLabTechnician_4");
list.add("Pathologist");
list.add("SeniorLabTechnician_6");
System.out.println(list.indexOf("Senior"));
}
}
I left overriding of lastindexof method for you.
private int getsearchPos(String searchvalue) {
for(String hj : Test)
{
if(hj.toLowerCase().startsWith(searchvalue.toLowerCase()))
return Test.indexOf(hj);
}
return -1;
}
this should help.
I want to add an object to my array. I am trying to create a method so whenever it's called, it adds the generic type object. Here's my code:
public class ArrayObjects<E> implements SomeImp<E>{
private E[] list;
private int maxCapacity, currentSize;
public ArrayObjects(){
maxCapacity = 10;
array = (E[]) new Object[maxCapacity];
}
public void addObj(E obj){
array.add(obj); //Throws an error
}
}
Eclipse shows me an error though. It says "Cannot invoke add(E) on the array type E[ ]"
Does anyone know why does this happen? Do you know of an alternative of adding an object to my generic array?
Thank you!
EDIT:
When I create an instance of a class that instantiates ArrayObjects, and try to add a value to it, it doesn't do it. code:
import packageWhereArrayObjectsIs.*;
public class Test {
private ArrayObjects<Integer> list;
public Test() {
list = new ArrayObjects<Integer>();
Test();
}
private void TestOne() {
for(int i=1; i <= 10; i++)
list.addLast(i);
System.out.println("Should print 1 .. 10");
System.out.println(list);
}
}
The method add() does not exist for arrays. You must access array elements using the correct syntax []:
public void addLast(E obj) {
array[currentSize++] = obj;
}
In order for your list to print nicely, you'll want to add a toString() method to your ArrayObjects class:
public String toString() {
return Arrays.toString(array);
}
To iterate over the elements of your ArrayObjects, you can implement the Iterable interface:
public class ArrayObjects<E> implements Iterable<E>
This requires your class to have an iterator() method that returns an Iterator:
public Iterator<E> iterator() {
class It implements Iterator<E>
{
int position = -1;
public boolean hasNext() {
return position + 1 < currentSize;
}
public E next() {
return array[++position];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
return new It();
}
Finally, this code shows how you can now iterate over your list using an enhanced for loop:
ArrayObjects<Integer> list = new ArrayObjects<Integer>();
for (int i = 0; i < 10; i++) list.addLast(i);
for (Integer i: list) {
System.out.println("Iterating over list! Next element is " + i);
}
You should do something like this, assuming that your actual size is 1 when you add your first element BUT the position will be 0 because it's the first position of the array.
public boolean addObj(E obj){
if(actualSize == maxCapacity){
return false;
}
array[actualSize--] = obj;
return true;
}
I changed the return value to return false if there is no positions left in the array (considering that you won't remove any object in the middle).
Why do you need an array? Why not going with a List?
public class ArrayObjects<E> implements SomeImp<E>{
private List<E> list;
private int maxCapacity;
public ArrayObjects(){
maxCapacity = 10;
list = new ArrayList<E>();
}
public boolean addObj(E obj){
if(list.size() == maxCapacity){
return false;
}
list.add(obj);
return true;
}
}
See that using a List you won't have to deal with the actualSize.
EDIT: as Smac89 points out, it makes no sense to use a list. But keep in mind you will have to find an empty position if the array is not full.
I was attempting to write some code for a program in BlueJ (Java) that lists bags and adds and removes items from those bags, that sort of thing. Then I got stuck in the first class; I couldn't get to add an item to the bag properly as you can notice below in the addItem() method; it keeps adding String s to every null element in the array rather the first encountered. Any help would be tremendously appreciated.
Best wishes & many thanks,
Xenos
public class Bag1 {
private String[] store; // This is an array holding mutlitple strings.
public Bag1(int storageCapacity) {
store = new String[storageCapacity];
} // That was the primitive array constructor.
public boolean isFull() {
boolean full = true;
for(int i = 0; i < store.length; i++) {
if(store[i] == null) {
full = false;
}
}
return full;
} // The method above checks if the bag is full or not, and returns a boolean value on that basis.
public void add(String s) {
for(int i = store.length; i >= 0; i--) {
if(store[i] == null) {
store[i] = s;
}
}
}
}
You should exit the loop after finding the first empty spot :
public void add(String s)
{
for(int i=store.length-1; i>=0; i--) { // note the change in the starting index
if(store[i]==null) {
store[i] = s;
break;
}
}
}
I have a very simple program and I just need to check an array for a value in it.
I have a class called bulkBean. this is it.
public class bulkBean {
private int installmentNo;
private double amount;
public int getInstallmentNo() {
return installmentNo;
}
public void setInstallmentNo(int installmentNo) {
this.installmentNo = installmentNo;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Now I have an array of this bulkBean type in my program, this is my program.
import java.util.Arrays;
public class test {
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
}
for(int j = 0; j< arr.length ;j++){
System.out.println("INFO: array "+j+" = "+arr[j]);
}
if (Arrays.asList(arr).contains(i) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] arg){
bulkBean bb1 = new bulkBean();
bb1.setInstallmentNo(1);
bb1.setAmount(5500);
bulkBean bb2 = new bulkBean();
bb2.setInstallmentNo(2);
bb2.setAmount(4520);
bulkBean[] bulkArray = new bulkBean[2];
bulkArray[0] = bb1;
bulkArray[1] = bb2;
boolean a = scan_bulkList(bulkArray,1);
System.out.println("val = "+a);
}
}
I create 2 instances of bulk bean and I set values to them. Then I added those two instances to an array. Then I pass that array to the method to check for a value(also given as a parameter. In this case it is 1.). If the array contains that value, it should return true, otherwise false.
whatever value I enter, it return false.
Why do I get this issue?
Arrays.asList() returns a List which has a single element - an array. So, you are actually comparing against an array. You need to compare against each value in the array.
As TheListMind told, Arrays.asList() taken on an int[] gives you a list containing the array.
Personally, I would construct directly the List instead of constructing the array, or even better (no need of array instanciation), test while iterating the bulk array :
for(int x=0;x<bulkList.length;x++){
if (bulkList[x].getInstallmentNo() == i){
return true;
}
}
return false;
The mistake you made here is , you created the int array which must be Integer array because Arrays.asList().contains(Object o); makes the input parameter also Integer(Integer i). int is not an object Integer is the object. Hope it will work.
int[] arr = new int[bulkList.length];
change to:
Integer[] arr = new Integer[bulkList.length];
Change the method as below to avoid complications:
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
if (bulkList[x].getInstallmentNo()==i) {
return true;
}
}
return false;
}