Got an assignment question which asks to return the first item from an array and then remove it. If the array is empty I should return null. Here is my code:
public String pop(){
if(arrayLength == 0){
return null;
}else{
String[] temp = new String[100];
String firstItem = StringStack[0];
for(int i = 1; i<StringStack.length; i++){
temp[i] = StringStack[i];
}
StringStack = temp;
return firstItem;
}
}
The arrayLength variable is set by this method and works fine:
public int getLength(){
int count = 0;
for (String s : StringStack) {
if (s != null) {
count++;
}
}
return count;
}
I cant figure out what it is I am doing wrong here. Another part of this question is I cant use any collections or Systems.arraycopy so I have to use for loops and other basic operators to solve this. It also has to be an array so I cant use array lists or other data structures.
here is version with two fixed problems:
public String pop() {
if(StringStack == null || StringStack.length == 0)
return null;
String firstItem = StringStack[0];
String[] temp = new String[StringStack.length-1]; // allocate proper size
for(int i = 1; i<StringStack.length; i++){
temp[i-1] = StringStack[i]; // i-1 for temp array
}
StringStack = temp;
return firstItem;
}
Related
I'm trying to remove an element from an array. I am running into an issue where when I run my program and remove a certain index. I get nulls in the place where the element/index should be removed entirely.
My output is when I execute list.display() in the main method is
Tom, Bob, Richard
However after I execute list.remove() and run the program. I get
null, null, Richard.
Any tips?
public class MyArrayList implements MyList {
private Object[] theList;
public MyArrayList()
{
theList = new Object[0];
}
public boolean add(Object toAdd){
if(toAdd != null) {
Object[] temp = new Object[theList.length + 1];
for(int i = 0; i < theList.length; i++) {
temp[i] = theList[i];
}
temp[theList.length] = toAdd;
theList = temp;
return true;
} else {
return false;
}
}
public Object remove(int index) {
if (index >= 0 && index < theList.length) {
Object[] temp = new Object[theList.length - 1];
theList[index] = null;
int j = 0;
for (int i = 0; i < theList.length; i++) {
if (i == index) {
continue;
}
temp[j++] = theList[i];
theList = temp;
}
return temp;
}
return null;
}
public class Main {
public static void main(String[] args) {
MyArrayList list = new MyArrayList();
list.add("Tom");
list.add("Bob");
list.add("Richard");
list.display();
list.remove(0);
list.remove(1);
list.display();
}
}
Where you call list.remove(0), you should be assigning the result back to list again. For example:
list = list.remove(0);
A couple of other things:
It's generally a bad idea to change the index variable within a loop. It's legal, but leads to logic errors that can be difficult to reason about and diagnose.
You're getting the null in your output because the remove method also mutates the theList when you execute:
theList[index] = null;
Since you're returning a copy of theList you don't need to also set that element of the theList array to null.
Since your code implements MyList which is not available in code, i could not run below sample on your code but you can have below logic in your code. You don't need extra temp array in remove method. Since it an array, you can start traversing array from index which has to be removed and start moving next element by one step before.
public Object remove(int index) {
if (theList == null || index < 0 || index >= theList.length) {
return theList;
}
for (int i = index; i < theList.length; i++) {
theList[i] = theList[i + 1];
}
return null;
}
You can trim array tail if it has more empty places based on some threshold.
the code is doing exactly what you asked it to do. Those removed values are null because you have this line
theList[index] = null;
Also think about what your intentions are.
list.remove(0); <- this will remove the first element so now list would be Rob, Richard
list.remove(1); <- this will remove the 2nd element of the modified list (Rob, Richard) so result would be Rob. This is probably not what you want.
instead of this
if (i == index) {
i++; // risk of out of bounds exception
}
you probably want this instead
if (i == index) {
continue;
}
public class MyArrayList<T> implements MyList<T>{
int num; //number of things in the list
T[] vals; //to store the contents
#SuppressWarnings("unchecked")
public MyArrayList() {
num = 0;
vals = (T[]) new Object[3];
}
public int size() { //returns number of things in the bag
return num;
}
public T get(int index) { //returns the indexth values
if((index < 0) || (index >= num))
throw new IndexOutOfBoundsException();
return vals[index];
}
#SuppressWarnings("unchecked")
public void add(T s) { //adds s to the list
if(num == vals.length) { //if array is full, make it bigger
T[] temp = (T[]) new Object[vals.length*2];
for(int i=0; i < num; i++)
temp[i] = vals[i];
vals = temp;
}
vals[num] = s;
num++;
}
public boolean contains(T s) { //returns whether s is list
for(int i=0; i < num; i++) { //ending condition should be num
if(vals[i].equals(s)) {
return true;
}
}
return false;
}
public T getUnique(){
T distinct = null;
int count = 0;
for (int i=0; i<vals.length; i++){
distinct = vals[i];
for (int j = 0; j<vals.length; j++){
if (vals[j] == vals[i]){
count++;
}
if (count == 1){
return distinct;
}
}
}
if (distinct == null){
throw new IllegalArgumentException();
}
return distinct;
}
public void addBefore(T input, T before){
for (int i = 0; i<vals.length; i++){
T temp = vals[i];
if(temp.equals(before)){
vals[i-1] = input;
}
}
}
public void removeLast(T s){
for (int i = vals.length; i>=0;i--){
if (vals[i].equals(s)){
vals[i] = vals[i+1];
}
}
}
}
I am working on the ArrayList implementation in Java. I have not been able to finish getUnique, removeLast and addBefore method. I can't seem to be working well with the arrays because I seem to have been replacing the values instead of adding it. A little help on what I am doing wrong.
In addBefore method you are rewritting content on index i-1 with your new varible, you are not adding it. You have to move the rest of the list one index to the right. Also try add new input before first element, it should crash.
In removeLast you are moving second to last variable to the last index (second to last = last). You should be just calling remove on last index.
I assume you want to return unique element in getUnique method. You are almost there, just look at the second for cycle. And btw you dont need help variable to save vals[i], you can just return vals[i].
The purpose of this code is to implement three stacks in a single array. I use linked node to implement stack. the elements are pushed into array one by one directly, and the elements in each stack are connected by previous pointer. the pointer is int value corresponding to index in array where the item is stored. nextAvaIndexmethod return next available index that can store new pushed item. Because there will space released in the beginning of the array after executing pop method. ifindexused < arr.lengthit will keep moving forward to store new item, while if indexusedreaches end of array, the method will search is there free space in beginning of array.
But when I run it, it throws NullPointerException, i know the meaning of this error, but I can't fix it. Thanks for your comments! Is the code correct? One more question of removal an item from int type array. I letarr[i].data = 0 to delete the item, and use statement arr[i].data == 0 to check if one space is null. But what if one space store0? Thanks for your suggestion!
public class FlexiblemultiStack {
private int[] toppoint = {-1, -1, -1};// assume number of stack ==3;
private int indexused = 0;
private stackNode[] arr;
public FlexiblemultiStack(int sizeEach, int stackNO) {
arr = new stackNode[sizeEach * stackNO]; //
}
public boolean isEmpty(int stackNum) {
return toppoint[stackNum] == 0;
}
public void push(int item, int stackNum) {
int lastIndex = toppoint[stackNum];
int nextIndex = nextAvaIndex();
if (nextIndex == -1) { // if nextIndex = -1, there is no more space!
System.out.println("There is no more space!");
} else {
toppoint[stackNum] = nextIndex;
arr[toppoint[stackNum]] = new stackNode(item, lastIndex);
indexused++;
}
}
public int pop(int stackNum) {
if (toppoint[stackNum] == -1) {
return 0;
} else {
int value = arr[toppoint[stackNum]].data;
int lastIndex = toppoint[stackNum];
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
arr[lastIndex] = null;
indexused--;
return value;
}
}
public int peek(int stackNum) {
return arr[toppoint[stackNum]].data;
}
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused].data != 0) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].data == 0) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}
public void print(int stackNum) {
while (toppoint[stackNum] != -1) {
System.out.print(arr[toppoint[stackNum]].data + "<--");
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
}
}
public void printarr(){
for(int i = 0; i< arr.length;i++){
System.out.print(arr[i]);
}
}
public class stackNode { // Exception in thread "main" java.lang.NullPointerException
List item
private int previous;
private int data;
public stackNode(int StackSize) {
this.previous = -1;
}
public stackNode(int value, int prev) {
data = value;
previous = prev;
}
}
}
Exception in thread "main" java.lang.NullPointerException
at stackandqueue.FlexiblemultiStack$stackNode.access$000(FlexiblemultiStack.java:86)
at stackandqueue.FlexiblemultiStack.nextAvaIndex(FlexiblemultiStack.java:61)
at stackandqueue.FlexiblemultiStack.push(FlexiblemultiStack.java:32)
at stackandqueue.StackandQueue.main(StackandQueue.java:71)
/Users/xchen011/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
In the pop() method, it appears you are denoting an open index by setting the array index to null (arr[lastIndex] = null). In nextAvaIndex() you check if the index is available by examining arr[i].data. If arr[i] has been set to null by pop(), you will get the NullPointerException. To make the definition of available consistent with the check for availability, try replacing arr[indexused].data != 0 with arr[indexused] != null and if(arr[i].data == 0) with if(arr[i] == null) in the nextAvaIndex() method.
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused] != null) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}
I am using Selenium Webdriver with Java binding and I'm testing a sorting functionality whereby you have values arranged in an arraylist = {"4"","4.5"","5.5""}. So basically the string contains decimal points as well as double quotation. I have the following code below. The problem is that I keep getting false due to the fact that when it compares the current to previous, it comes with false. Thanks for your help
public Boolean checkAscendingOrderScreensize(List<String> list){
if(list == null || list.isEmpty())
return false;
if(list.size() == 1)
return true;
for(int i=1; i<list.size();i++)
{
String current = list.get(i).toString();
String previous = list.get(i-1).toString();
current = current.replace(",",".");
current = current.replace("\"", "");
previous = previous.replace(",",".");
previous = previous.replace("\"", "");
if(current.compareTo(previous)>0)
return false;
}
return true;
}
You will need to covert the string to double before conversion. So the workaround will be
public class Main {
public static void main(String bicycle[]) {
List<String> texts = new ArrayList<String>();
texts.add("4\"");
texts.add("4.5\"");
texts.add("5.5\"");
System.out.println(checkAscendingOrderScreensize(texts));
// prints true
}
public static boolean checkAscendingOrderScreensize(List<String> list) {
if (list == null || list.isEmpty())
return false;
if (list.size() == 1)
return true;
for (int i = 1; i < list.size(); i++) {
String current = list.get(i).toString();
String previous = list.get(i - 1).toString();
current = current.replace(",", ".");
current = current.replace("\"", "");
previous = previous.replace(",", ".");
previous = previous.replace("\"", "");
if(Double.valueOf(current)<Double.valueOf(previous))
return false;
}
return true;
}
}
Basically I have a main class which I declare my objects in and then in my Person class I have a method that is meant to add and object to an array created in Person class. For some reason this works for the first item but all the rest just return false (returns true if the item was added to array and false if the item was not added to the array). Here is my main method:
Department dept = new Department(4);
Person john = new Person("John", 35);
System.out.println(dept.addPerson(john));
and the class that is not working:
private Person[] people;
private int count;
public Department(int count){
people = new Person[count];
}
public boolean addPerson(Person x){
boolean found = false;
for(int i = 0; i < people.length; i++){
if (people[i] == null){
people[i] = x;
found = true;
}
}
return found;
}
Your first call to the method, you're filling the entire array. So the indices will not be null the next call
public boolean addPerson(Person x){
boolean found = false;
for(int i = 0; i < people.length; i++){ // you're filling the array in this loop
if (people[i] == null){
people[i] = x;
found = true;
}
}
return found;
}
You need to break your for loop after you add something. You fill up your array with the first person you add now.
for(int i = 0; i < people.length; i++){
if (people[i] == null){
people[i] = x;
found = true;
}
}
Should be
for(int i = 0; i < people.length; i++){
if (people[i] == null){
people[i] = x;
found = true;
break;
}
}