Finding min and max value in a oop - java

Can I please get help with this java code? I am trying to output the min and max value of element from an array list but it's only outputting the first element added to the list and the last element added to the list. Can someone please tell me what the error might be?
Here is my code:
import java.util.ArrayList;
//import java.util.Collections;
public class ClassName{
private String fieldName;
private ArrayList<SubClass> list = new ArrayList<>();
public ClassName(String a) {
fieldName = a;
}
public String getFieldName() {
return fieldName;
}
public void addSub(SubClass b) {
list.add(b);
}
public void addSub(String b, double c) {
list.add(new SubClass(b, c));
}
public boolean haveSub(String b, double c) {
return list.contains(new SubClass(b, c));
}
public SubClass getSubByName(String b) {
String d = b;
for (Sub elem : list) {
d += elem;
return elem;
}
return null;
}
public SubClass closest() {
SubClass min = list.get(0);
for (int i = 1; i > list.size(); i++) {
SubClass minC = list.get(i);
if (min.equals(minC)) {
min = list.get(i);
}
}
return min;
}
public SubClassfurthest() {
SubClass max = list.get(0);
for (int i = 0; i < list.size(); i++) {
Planet maxC = list.get(i);
if (max.equals(maxC)) {
max = list.get(i);
}
}
return max;
}
#Override
public String toString() {
String s = "...text..." + fieldName + " ...text...:\n";
for (SubClass elem : list){
s += elem.toString();
}
return s;
}
}

From names being employed I believe you intend to compare by 'distance' (presumably distance from Sun?). Assuming this to be true and that the Planet class includes a getDistanceFromSun() method then you can do something like this. Finding the furthest Planet would work the same way except you switch the operator (or swap the operands).
public Planet findClosestToSun() {
Planet closest = null;
for (Planet planet : planets) {
if (null == closest || planet.getDistanceFromSun() < closest.getDistanceFromSun()) {
closest = planet;
}
}
return closest;
}

Related

The for each loop for the custom data type (ArrayList) with self implemented iterator does not run

import java.util.Arrays;
import java.util.Iterator;
public class ArrayList<Type> implements Iterable<Type> {
Type[] arr = (Type[]) new Object[10];
int size = 0;
//change capacity
public void newCapacity(int i) {
if (i == 0) {
int newIncreasedCapacity = arr.length * 2;
arr = Arrays.copyOf(arr, newIncreasedCapacity);
} else if (i == 1) {
int newDecreasedCapacity = arr.length / 2;
arr = Arrays.copyOf(arr, newDecreasedCapacity);
}
}
// add an item
public void add(Type item) {
if (size == arr.length) {
newCapacity(0);
}
arr[size++] = item; //increases size after appending
}
//remove an item
public Type remove(int index) {
if (size <= arr.length / 4) {
newCapacity(1);
}
Type removedItem = (Type) arr[index];
for (int i = index; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size -= 1;
return removedItem;
}
public int size() {
int count = 0;
for (int i = 0; i < size; i++) {
count += 1;
}
return count;
}
#Override
public Iterator<Type> iterator() {
return new ArrayIterator(arr);
}
class ArrayIterator<Type> implements Iterator<Type> {
private Type[] arrayList;
public ArrayIterator(Type[] newArray) {
arrayList = newArray;
}
// check if next element not null
public boolean hasNext() {
return (arrayList[size + 1] != null);
}
// next element
public Type next() {
if (arrayList[size + 1] != null) {
return (arrayList[size + 1]);
} else {
return null;
}
}
}
// Main Method
public static void main(String[] args) {
ArrayList<Integer> new_arr = new ArrayList<>();
new_arr.add(5);
new_arr.add(7);
new_arr.add(9);
new_arr.remove(0);
System.out.println(new_arr.size());
for (int i : new_arr) {
System.out.println(new_arr.size());
System.out.println(i);
}
}
}
I implemented the code for a custom ArrayList and also implemented an iterator for my custom data type, but I am facing an issue.
So when i run the for each loop in the main method, the loop does not run and thus nothing is printed on the console.I have checked the array which is being used for the for-each loop is not empty.Please help!
I think that you should fix your Iterator to something like
class ArrayIterator<Type> implements Iterator<Type> {
private Type[] arrayList;
private int position;
public ArrayIterator(Type[] newArray) {
arrayList = newArray;
position = 0;
}
// check if next element not null
public boolean hasNext() {
return (position != size);
}
// next element
public Type next() {
if (arrayList[position] != null) {
return (arrayList[position++]);
} else {
return null;
}
}
}
You are using the position of the size of the array to calculate the next() and hasNext(), the hasNext() is always returning null.

How do I sort an ArrayList of strings in alpabetical order using a compareTo method?

I'm an amateur programmer and I've created a program that contains an arraylist that holds different phone book contacts and I'm trying to sort the arraylist lexicographically using a compareTo method. I don't know how to properly call the method in the main method so that it sorts properly and I'm not allowed to use collections sort. Can anyone help me?
Here's some of my code:
public class Phonebook implements Comparable<Phonebook> {
private String first, last;
public Contact(String first, String last) {
this.first = first;
this.last= last;
}
public String getFirst() {return first;}
public String getLast() {return last;}
public String toString() {
return first + " " + last;
}
public int compareTo(Phonebook another) {
int a = last.compareTo(another.last);
int b = first.compareTo(another.first);
if (a== 0 && b== 0)
return 0;
if (a == 0 && b!= 0)
return b;
return a;
}
}
public class PhonebookList implements Iterable<Phonebook>{
ArrayList<Phonebook>phonebook;
public PhonebookList() {
}
public PhonebookList(Contact[]contacts) {
phonebook=new ArrayList<>(Arrays.asList(phonebooks));
}
import java.util.*;
public static void main(String[] args) {
// TODO Auto-generated method stub
PhonebookList list= new PhonebookList();
Phonebook ph1= new Phonebook ("Brandon","Johnson");
Phonebook ph2 = new Phonebook ("Samantha","Joseph");
list.add(ph1);
list.add(ph2);
}
The compare to method returns 1 if the item is "larger", 0 if they are equal or -1 if the item is "smaller".
This should work:
int compareTo (PhoneBook o) {
for(int i = 0; i < first.size(); i++) {
if (i >= o.first.size())
return 1;
if ((int)first.charAt(i) > (int)o.first.charAt(i))
return -1;
else if ((int)first.charAt(i) < (int)o.first.charAt(i))
return 1;
}
for(int i = 0; i < last.size(); i++) {
if (i >= o.last.size())
return 1;
if ((int)last.charAt(i) > (int)o.last.charAt(i))
return -1;
else if ((int)last.charAt(i) < (int)o.last.charAt(i))
return 1;
}
return 0;
}
This just checks if the ASCII value is larger. (All letters have to be lower- or uppercase)

Implementing a Priority Queue as a Stack Java

I've implemented my program but I am getting an exception java.lang.ClassCastException
This is the code:
import java.util.NoSuchElementException;
public class BasePQStack<Item> implements Stack<Item> {
// TODO: implement this object.
private int N = 0;
private MaxPQ<Compare> pq = new MaxPQ<>();
private int count;
public BasePQStack() {
count = 0;
}
/**
* entry point for sample output..
*
* #param args
*/
public static void main(String[] args) {
Stack<Integer> S = new BasePQStack<Integer>();
S.push(new Integer(2));
S.push(new Integer(7));
Integer W = S.pop();
S.push(new Integer(8));
S.push(new Integer(5));
;
Integer X = S.pop();
Integer Y = S.peek();
S.push(new Integer(3));
Integer Z = S.pop();
System.out.println("Testing: ");
System.out.println(W);
System.out.println(X);
System.out.println(Y);
System.out.println(Z);
}
#Override
public Item push(Item item) {
Compare x = new Compare(item, count);
pq.insert(x);
count++;
N++;
return item;
}
#Override
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("no such element");
else {
Item var = (Item) pq.delMax();
N--;
return var;
}
}
#Override
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("no such element");
else {
Item var = (Item) pq.delMax();
push(var);
return var;
}
}
#Override
public boolean isEmpty() {
return N == 0;
}
#Override
public int size() {
return N;
}
public class Compare implements Comparable<Compare> {
private Item value;
private int a;
public Compare(Item value, int a) {
this.a = a;
this.value = value;
}
#Override
public int compareTo(Compare x) {
if (this.a > x.a)
return 1;
if (this.a < x.a)
return -1;
else
return 0;
}
public int getA() {
return this.a;
}
public Item getValue() {
return this.value;
}
#Override
public String toString() {
return "item {" + "value = " + value + ",a = " + a + '}';
}
}
}
The message I am getting from the console is BasePQStack$Compare cannot be cast to java.lang.Integer. I've tried to do many castings but could not figure anything out as it just led to more error
The output of the code should be:
7
5
8
3
You should probably replace this line
Item var = (Item) pq.delMax()
With
Item var = (Item) pq.delMax().getValue();
Because delMax() returns a compare object and you need a Item object.
From the Java documentation: Class cast exceptions are "thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance".
From the code you posted, it looks like it could be occurring when you attempt to cast something to an Item:
Item var = (Item) pq.delMax();
Probably because your queue does not contain objects of type Item, it contains objects of type Compare. In general be careful when you decide to downcast because the compiler errors are there to help you.
Your MaxPQ Key is of type Compare and when you push an Integer it gets wrapped in a Compare before being inserted into the MaxPQ.
The problem is when you pop or peek you do not do any unwrapping of the Compare to get back to the Integer. This is why you get a ClassCastException on any line that calls pop() or peek(). You are treating the Compare as if it is an Integer.
You need to modify your pop() and peek() methods as follows;
#Override
public Item pop() {
if (isEmpty()) {
throw new NoSuchElementException("no such element");
} else {
Item var = (Item) pq.delMax().getValue();
N--;
return var;
}
}
#Override
public Item peek() {
if (isEmpty()) {
throw new NoSuchElementException("no such element");
} else {
Item var = (Item) pq.delMax().getValue();
push(var);
return var;
}
}
Note the use of getValue(). This is what does the unwrapping I mentioned above i.e. it gets the Integer out of the Compare for you.

Implement a Set class using an array

My Java assignment is to implement a set class by using an array.
The assignment won't allow me import the set class from the library, so I have to make it on my own. When I tried to print out the array, it prints out numbers in repeats, not unique numbers. I don't know where the problem is, so if you guys can find any errors in my code, it would be great. I tried to add numbers 2, 3, and 4 to the set, so the result should be 2 3 4, but the code shows me 2 3 2 3 2.
I think the source of the problem is from the add method from the set class, but I don't know what the problem is exactly.
import java.util.Arrays;
public final class Set implements SetInterface
{
private int[] set;
private int size;
private int capacity;
public Set(int c)
{
capacity = c;
set = new int[capacity];
size = 0;
}
public boolean contains(int x)
{
boolean contains = false;
for(int i = 0; i<capacity; i++)
{
if(x == set[i])
contains = true;
else
contains = false;
}
return contains;
}
public void add(int x)
{
for(int i = 0; i<capacity; i++)
{
if(!contains(x))
{
if(size == capacity)
{
set = Arrays.copyOf(set,size*2);
}
if(set[i]==0)
{
set[i++] = x;
}
}
}
size++;
}
public boolean remove(int x)
{
boolean remove = false;
for(int i = 0; i < capacity; i++)
{
if(x == set[i])
{
set[i] = set[size -1];
size--;
remove = true;
}
if(isEmpty())
{
remove = false;
}
}
return remove;
}
public void clear()
{
set = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
if(size == 0)
return true;
else
return false;
}
public int[] toArray()
{
return Arrays.copyOf(set, capacity);
}
}
This is the driver class that I test my class.
import java.util.Arrays;
public class SetDriver
{
public static void main(String[] args)
{
SetDriver driver = new SetDriver();
Set s1 = new Set(5);
s1.add(2);
s1.add(3);
s1.add(4);
driver.print(s1);
System.out.println("Size: "+s1.size());
}
public static void print(Set s)
{
for(int i = 0; i<s.toArray().length; i++)
{
System.out.print(s.toArray()[i]+" ");
}
System.out.println("");
}
}
The outputs are here:
2 3 2 3 2
Size: 3
There's a likely problem with your contains method. Suppose that you did find a duplicate. What happens is that you assign your variable to true and you continue to iterate. This stomps over the logic entirely; you could have a duplicate but never act on it because your boolean code precludes you from doing so.
Ideally, when you find a match, you must stop iterating and return immediately.
public boolean contains(int value) {
for(int setItem : set) {
if(setItem == value) {
return true;
}
}
return false;
}
You should change add method like this.
public void add(int x) {
if (contains(x))
return;
if (size >= capacity) {
capacity *= 2;
set = Arrays.copyOf(set, capacity);
}
set[size++] = x;
}

I have ONE pre-compile error

Here is the assignment:
Modify the maze problem in Chapter 4 so that it can start from a user defined starting position (other than 0, 0) and search for a user defined ending point.
The whole program seems to look fine, and I still have to mess with the user-inputted part, but there is one line that has an error and I don't know how to get rid of it. Any help would be appreciated.
The line that has the error is:
StackADT stack = new LinkedStackADT ();
And it is telling me that LinkedStackADT cannot be resolved to a type.
Also, how do I get the maze to take in user-defined starting positions and ending points? Thanks for any possible help!
public class Maze
{
public interface StackADT<T> {
public void push (T element);
public T pop();
public T peek();
public boolean isEmpty();
public int size();
public String toString();
}
public static void main(String[] args){
abstract class LinkedStack<T> implements StackADT<T>
{
private int count;
private LinearNode<T> top;
public LinkedStack()
{
count = 0;
top = null;
}
class LinearNode<T>
{
private LinearNode<T> next;
private T element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode(T elem)
{
next = null;
element = elem;
}
public LinearNode<T> getNext()
{
return next;
}
public void setNext(LinearNode<T> node)
{
next = node;
}
public T getElement()
{
return element;
}
public void setElement(T elem)
{
element = elem;
}
}
class Position
{
private int x;
private int y;
Position ()
{
x = 0;
y = 0;
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
public void setx1(int a)
{
x = a;
}
public void sety(int a)
{
y = a;
}
public void setx(int x2) {
}
}
private final int TRIED = 3;
private final int PATH = 7;
private int [][] grid = {{1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,0,1,1,0,1,1,1,1,0,0,1},
{1,1,1,1,1,0,1,0,1,0,1,0,0},
{0,0,0,0,1,1,1,0,1,0,1,1,1},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1}};
public StackADT<Position> push_new_pos(int x, int y,
StackADT<Position> stack)
{
Position npos = new Position();
npos.setx1(x);
npos.sety(y);
if (valid(npos.getx(),npos.gety()))
stack.push(npos);
return stack;
}
public boolean traverse ()
{
boolean done = false;
Position pos = new Position();
Object dispose;
StackADT<Position> stack = new LinkedStackADT<Position> ();
stack.push(pos);
while (!(done))
{
pos = stack.pop();
grid[pos.getx()][pos.gety()] = TRIED; // this cell has been tried
if (pos.getx() == grid.length-1 && pos.gety() == grid[0].length-1)
done = true; // the maze is solved
else
{
stack = push_new_pos(pos.getx(),pos.gety() - 1, stack);
stack = push_new_pos(pos.getx(),pos.gety() + 1, stack);
stack = push_new_pos(pos.getx() - 1,pos.gety(), stack);
stack = push_new_pos(pos.getx() + 1,pos.gety(), stack);
}
}
return done;
}
private boolean valid (int row, int column)
{
boolean result = false;
if (row >= 0 && row < grid.length &&
column >= 0 && column < grid[row].length)
if (grid[row][column] == 1)
result = true;
return result;
}
public String toString ()
{
String result = "\n";
for (int row=0; row < grid.length; row++)
{
for (int column=0; column < grid[row].length; column++)
result += grid[row][column] + "";
result += "\n";
}
return result;
}
}
}
}
You don't have a type (or a class) defined as LinkedStackADT. You do have a type LinkedStack, but it's abstract so the new will fail. If you remove the abstract keyword from LinkedStack, it should be instantiatable. (note: instantiatable is not a real word)

Categories