I have to create a public method called cancelPolicy(int polNum) which removes the policy from the client's list with the given policy number, if found. It should return true if the policy was found, otherwise it should return false. When a policy is removed from the array, the empty location in the array should be replaced by the last policy in the array.
The code I have written so far:
public int cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
}
}
return polNum;
}
What I don't understand is how to remove and replace from the array of policies[i].
This is precisely what you are looking for:
public boolean cancelPolicy(int polNum)
{
int n = policies.length-1; //optimization by making n = length-1
for (int i = 0; i <= n; i++) { //notice equals in condition
if (policies[i].getPolicyNumber() == polNum) {
policies[i] = policies[n]; //replace i with last if that's what you meant
policies[n] = null; //remove loitering
return true;
}
}
return false;
}
To replace the found policy, you need to do as follow:
public boolean cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
policies[i] = policies[arrSize - 1];
policies[arrSize - 1] = null;
arrSize--;
return true;
}
}
return false;
}
And in you class you need to keep the number of policies:
private int arrSize;
Alternatively you can recreate the array:
public boolean cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
int[] newArr = new int[policies.length - 1];
System.arraycopy(policies, 0, newArr , 0, i);
System.arraycopy(policies, i + 1, newArr, i, policies.length - i - 1);
policies = newArr;
return true;
}
}
return false;
}
And the best, but not sure if this option is available to you, would be to use a List or a Map
you cold get the last non null and then set the last element to null as well. this would "replace" it so you don't get duplicated policies. teachers like it when you think about stuff like that typically
public boolean cancelPolicy(int polNum){
for (int i = 0; i < policies.length; i++) {
if (policies[i].getPolicyNumber() == polNum) {
for (int j = policies.length - 1; j >=0; j--){
if (policies[j] != null) {
policies[i] = policies[j];
policies[j] = null;
return true;
}
}
}
}
return false;
}
Related
I know this question has been asked but I couldn't use the solutions of it to do what I want to do
My problem is every time I call from the function and enter an Id it always tells me that the id was removed even if I entered an id that was never entered it still prints the same
any tip and help would be appreciated :)
Note: I don't want to use ArrayList in it
here is my code :
public Members[] deleteMembers(String id) {
if (id == null)
return member;
Members[] copyId = new Members[member.length - 1];
for (int i = 0, k = 0; i < member.length; i++) {
if (member[i].getId().equals(id)) {
continue;
}
copyId[k++] = member[i];
}
return copyId;
}
You have only one problem. Do not forget, that array could not have an item with a given id.
public static Member[] deleteMember(String id, Member[] members) {
if (id == null || members == null)
return members;
int pos = findMemberPos(id, members);
if (pos == -1)
return members;
Member[] arr = new Member[members.length - 1];
for (int i = 0, j = 0; i < members.length; i++)
if (i != pos)
arr[i] = members[j++];
return arr;
}
private static int findMemberPos(String id, Member[] members) {
for (int i = 0; i < members.length; i++)
if (id.equalsIgnoreCase(members[i].getId()))
return i;
return -1;
}
That should work
public Members[] deleteMembers(String id) {
if (id == null)
return member;
if (!doArrayContainsId(id)) {
return member;
}
Members[] copyId = new Members[member.length - 1];
for (int i = 0, k = 0; i < member.length; i++) {
if (member[i].getId().equals(id)) {
continue;
}
copyId[k++] = member[i];
}
return copyId;
}
public boolean doArrayContainsId(String id) {
if (id == null) {
return false;
}
boolean doArrayContainsId = false;
for (Members members : member) {
if (members.getId().equals(id)) {
doArrayContainsId = true;
break;
}
}
return doArrayContainsId;
}
Btw you should try to name your classes a bit better like Member instead of Members since one object is one member and array or list of them should be called members
I would like to apologise in advance if im doing something wrong with the code formatting because this is my second time posting here
I have a java assignment due in a couple of days in which the user enters a string and only the integers are collected from it and placed in the array intArray
Now i think i got the logic right in the code below but when i run it in the main, it asks for the string and the boolean, when i enter both it gives me the error
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 115"
This is what i entered for example
"Enter a string and true if you want to skip errors or false if you want to skip errors
sdak23
false"
this is my main:
import java.util.Scanner;
public class MainStringToIntArray {
public static void main(String[] args) {
Scanner intut = new Scanner(System.in);
Scanner input = new Scanner(System.in);
StringToIntArray s1 = new StringToIntArray();
System.out.println("Enter a string and true if you want to skip errors or false if you want to skip errors");
s1.scanStringToIntArray(intut.next(), input.nextBoolean());
}
}
import java.util.Arrays;
import java.util.Scanner;
public class StringToIntArray {
private int[] intArray = new int[10];
public StringToIntArray() {
Arrays.fill(intArray, Integer.MIN_VALUE);
}
public int indexOf(int intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == intToFind) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public int indexOf(String intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == Integer.parseInt(intToFind)) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public boolean contains(int intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public boolean contains(String intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public int get(int index) {
if(index < 0 && index > 10) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
public boolean scanStringToIntArray(String s, Boolean skipErrors) {
Boolean result = null;
Scanner input = new Scanner(s);
int l = s.length();
if ((skipErrors)) {
String discard = null;
for (int a = 0; a < l; a++) {
for (int z = 0; z < l; z++) {
if (input.hasNextInt(s.charAt(z))) {
intArray[a] = s.charAt(z);
System.out.println(a);
result = true;
}
else {
discard = discard + s.charAt(z);
}
}
}
}
else {
for (int v = 0; v < l; v++) {
for (int p = 0; p < l; p++) {
if ((input.hasNextInt(s.charAt(p)))) {
intArray[v] = s.charAt(p);
System.out.println(v);
}
else {
System.out.println(v);
result = false;
}
}
}
}
return result;
}
}
The issue is in the get method. It is logically impossible for the index to be both less than 0 and greater than 10; you probably want to use the logical or operator (||). Also, the maximum index of the array is actually 9, as arrays are zero indexed.
public int get(int index) {
if(index < 0 || index > 9) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
There are other logical errors in your code as well. All your indexOf methods should be returning the index where the element was first found instead of the element itself and your else branch is always resetting it to -1 each time it is not found.
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;
}
}
Im running my code, and after it says the first print statement it pauses. It pauses at a point where it calls a function "insert" and simply doesnt respond anything. it prints "adding dog, cat, & horse" but then just stops, doesnt do anything after that.
main function
package assignment2;
public class Main {
public static void main(String[] args) {
OrderedStringList myList = new OrderedStringList(5);
System.out.println("adding dog, cat, & horse");
myList.Insert("dog");
myList.Insert("cat");
myList.Insert("horse");
myList.Display();
System.out.println("Value pig find = "+ myList.Find("pig"));
System.out.println("Value horse find = "+ myList.Find("horse"));
System.out.println("Adding mouse & rat");
myList.Insert("mouse");
myList.Insert("rat");
myList.Display();
System.out.println("myList size: "+ myList.Size());
if (!myList.Insert("chinchilla"))
System.out.println("Could not add chinchilla, full");
System.out.println("Removing dog, adding chinchilla.");
myList.Delete("dog");
myList.Insert("chinchilla");
myList.Display();
}
}
here is my code of functions
package assignment2;
public class OrderedStringList {
int length;
int numUsed;
String[] storage;
boolean ordered;
public OrderedStringList(int size){
length = size;
storage = new String[length];
numUsed = 0;
}
public boolean Insert(String value){
boolean result = false;
int index = 0;
if (numUsed < length) {
while (index < numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
moveItemsDown(index);
storage[index] = value;
numUsed++;
result = true;
}
return result;
}
private void moveItemsDown(int start){
int index;
for (index = numUsed-1; index >=start; index--){
storage[index+1] = storage[index];
}
}
private void moveItemsUp(int start){
int index;
for (index = start; index < numUsed-1; index++){
storage[index] = storage[index+1];
}
}
public boolean Find(String value){
return (FindIndex(value) >= 0);
}
private int FindIndex(String value) {
int result = -1;
int index = 0;
boolean found = false;
while ((index < numUsed) && (!found)) {
found = (value.equals(storage[index]));
if (!found)
index++;
}
if (found)
result = index;
return result;
}
public boolean Delete(String value){
boolean result = false;
int location;
location = FindIndex(value);
if (location >= 0) {
moveItemsUp(location);
numUsed--;
result = true;
}
return result;
}
public void Display() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.println(index+" "+storage[index]);
}
System.out.println("-------------");
System.out.println();
}
public void DisplayNoLF() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.print(storage[index]+" ");
}
System.out.println("-------------");
System.out.println();
}
public int Size(){
return numUsed;
}
}
You're getting caught in an infinite loop in the while statement of your Insert function. Consider this piece of code:
while (index < numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
What happens if compare >= 0 for index = 0? Index doesn't increment upwards, then the while loop is called again on index = 0, ad infinitum. You need to increment index outside of the if statement and put a different condition in your if statement.
while (index < numUsed && storage[index].compareTo(value) < 0) {
index++;
}
solved my problem by doing this. i simply removed the for loop and added an extra requirement on the while loop.