Did I mess up a constructor/method in this? - java

I don't get what is wrong. Something defintely is. I am just a noob. The idea is I put in all these parameters and run it on the TestMyInteger class. I am getting a major error Exception in thread "main" java.lang.NoClassDefFoundError: MyInteger
at TestMyInteger.main(TestMyInteger.java:3)
Caused by: java.lang.ClassNotFoundException: MyInteger
I can't figure out what is wrong with my code
public class MyInteger {
private int value;
public MyInteger (int value) {
this.value = value;
} //myInteger
public int getValue() {
return value;
}//getValue
public boolean isEven() {
return (value % 2 == 0);
}//isEven(not static)
public boolean isOdd() {
return (value % 2 != 0);
}//isOdd(not static)
public boolean isPrime() {
int i = 0;
for(i = 2; i <= value / 2; i++){
if(value % i != 0)
return true;
}
return false;
}//isPrime (not static)
public static boolean isEven (int n) {
return (n % 2 == 0);
}//isEven(static)
public static boolean isOdd(int n) {
return (n % 2 != 0);
}//isOdd(static)
public static boolean isPrime(int n) {
int i = 0;
for(i = 2; i <= n / 2; i++){
if(n % i != 0)
return true;
}
return false;
}//isPrime(static)
public static boolean isEven(MyInteger n) {
return n.isEven();
}// myInteger isEven
public static boolean isPrime(MyInteger o) {
int i = 0;
for(i = 2; i <= o / 2; i++){
if(o % i != 0)
return true;
}
return false;
} //myInteger prime
public static boolean isOdd(MyInteger o) {
return (o % 2 != 0);
}//MyInteger isOdd
public boolean equals(int anotherNum) {
if (n1 == n2)
return true;
return false;
} //what value is this (equals)
public boolean equals(MyInteger o) {
if (n1 == n2)
return true;
return false;
`enter code here` }//MyInteger equals
}
All of this will be run on this TestMyInteger class
public class TestMyInteger {
public static void main(String[] args) {
MyInteger n1 = new MyInteger(5);
System.out.println("n1 is even? " + n1.isEven());
System.out.println("n1 is prime? " + n1.isPrime());
System.out.println("15 is prime? " + MyInteger.isPrime(15));
System.out.println("15 is even? " + MyInteger.isEven(15));
MyInteger n2 = new MyInteger(24);
System.out.println("n2 is odd? " + n2.isOdd());
System.out.println("45 is odd? " + MyInteger.isOdd(45));
System.out.println("n1 is equal to n2? " + n1.equals(n2));
System.out.println("n1 is equal to 5? " + n1.equals(5));
System.out.println("n2 is even? " + MyInteger.isEven(n2));
System.out.println("n2 is odd? " + MyInteger.isOdd(n2));
System.out.println("n2 is prime? " + MyInteger.isPrime(n2));
}
}//TestMyInteger

Delegate, don't re-implement the same methods over and over. In order to access the value from a MyInteger instance you need to use instance.value. Your isPrime logic appears to be inverted. Don't try and change the signature of Object.equals(Object). If you plan to override equals, you should override hashCode and toString as well. Like,
public class MyInteger {
private int value;
public MyInteger(int value) {
this.value = value;
} // myInteger
public int getValue() {
return value;
}// getValue
public boolean isEven() {
return isEven(value);
}// isEven(not static)
public boolean isOdd() {
return isOdd(value);
}// isOdd(not static)
public boolean isPrime() {
return isPrime(value);
}// isPrime (not static)
public static boolean isEven(int n) {
return (n % 2 == 0);
}// isEven(static)
public static boolean isOdd(int n) {
return !isEven(n);
}// isOdd(static)
public static boolean isPrime(int n) {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}// isPrime(static)
public static boolean isEven(MyInteger n) {
return isEven(n.value);
}// myInteger isEven
public static boolean isPrime(MyInteger o) {
return isPrime(o.value);
} // myInteger prime
public static boolean isOdd(MyInteger o) {
return isOdd(o.value);
}// MyInteger isOdd
public boolean equals(int anotherNum) {
return value == anotherNum;
} // what value is this (equals)
#Override
public boolean equals(Object o) {
if (o instanceof MyInteger) {
return equals(((MyInteger) o).value);
}
return false;
}// MyInteger equals
#Override
public int hashCode() {
return Integer.hashCode(value);
}
#Override
public String toString() {
return String.valueOf(value);
}
}
Until you can compile MyInteger, you can't use MyInteger. The computer doesn't know how.

public final class MyInteger {
private final int value;
public MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean isEven() {
return isEven(value);
}
public boolean isOdd() {
return isOdd(value);
}
public boolean isPrime() {
return isPrime(value);
}
public static boolean isEven(int value) {
return value % 2 == 0;
}
public static boolean isOdd(int value) {
return !isEven(value);
}
public static boolean isPrime(int value) {
if (Math.abs(value) < 2)
return false;
for (int i = 2, max = (int)Math.sqrt(value); i <= max; i++)
if (value % i == 0)
return false;
return true;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
return obj instanceof MyInteger && value == ((MyInteger)obj).value;
}
#Override
public int hashCode() {
return Objects.hash(value);
}
#Override
public String toString() {
return String.valueOf(value);
}
}

Related

percentage of filled array in java

In this class I need if the array tabletet is filled 75% or not
It has to be with a method (readyPorosia) it is filled
Any better sugestions please
public class Porosia
{
private String shifraPorosia;
private int pozita;
private Tableti [] tabletet;
/* */
public Porosia(String sh, int nr)
{
tabletet = new Tableti[nr];
shifraPorosia = sh;
}
public void addTablet(Tableti t)
{
if(t == null){
System.out.println("Tablet can't be added");
}else if(full()){
System.out.println("Tablet can't be added.It's full");
}else{
tabletet[pozita++] = t;
System.out.println("Tablet added");
}
}
public boolean full()
{
if(pozita >= tabletet.length){
return true;
}
return false;
}
public boolean readyPorosia(Tableti [] t)
{
///in here to find the percentage of how much is filled the array
if(percentage >= 75){
return true;
}
return false;
}
public static void main(String[] args)
{
Porosia por = new Porosia("12122/2015",50);
por.addTablet(new Tableti("Samsung",7));
por.addTablet(new Tableti("Apple",10));
por.addTablet(new Tableti("Dell",20));
Tableti t4 = new Tableti("Lenovo",2);
por.addTablet(t4);
por.readyPorosia(por);
}
}
If you need the filled percentage, it's 100*pozita/tabletet.length. You can compare that number to 75.
public boolean readyPorosia(Tableti [] t)
{
int percentage = 100*pozita/tabletet.length;
if(percentage >= 75){
return true;
}
return false;
}

mostFrequent method bags adt(abstract data types)

I am trying to implement a method named mostFrequent in a bag that finds the most frequent object in a bag For example, if B = {Bob, Joe, Bob, Ned, Bob, Bob}, then the method
returns Bob. Hint: The method is O(n^2).
public E MostFrequent (Bag<E> B){
// implementation here
}
The adt of the bag is the following:
package edu.uprm.ece.icom4035.bag;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StaticBag implements Bag {
private int currentSize;
private Object elements[];
private class BagIterator implements Iterator {
private int currentPosition;
public BagIterator(){
this.currentPosition = 0;
}
#Override
public boolean hasNext() {
return this.currentPosition < currentSize;
}
#Override
public Object next() {
if (hasNext()){
return elements[this.currentPosition++];
}
else {
throw new NoSuchElementException();
}
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public StaticBag(int maxSize){
if (maxSize < 1){
throw new IllegalArgumentException("Max size must be at least 1.");
}
this.currentSize = 0;
this.elements = new Object[maxSize];
}
#Override
public void add(Object obj) {
if (obj == null){
throw new IllegalArgumentException("Value cannot be null.");
}
else if (this.size() == this.elements.length){
throw new IllegalStateException("Bag is full.");
}
else {
this.elements[this.currentSize++] = obj;
}
}
#Override
public boolean erase(Object obj) {
int target = -1;
for (int i=0; i < this.size(); ++i){
if (this.elements[i].equals(obj)){
target = i;
break;
}
}
if (target == -1){
return false;
}
else {
this.elements[target] = this.elements[this.currentSize-1];
this.elements[this.currentSize-1] = null;
this.currentSize--;
return true;
}
}
#Override
public int eraseAll(Object obj) {
int copies = 0;
while(this.erase(obj)){
copies++;
}
return copies;
}
#Override
public int count(Object obj) {
int counter = 0;
for (int i=0; i < this.size(); ++i){
if (elements[i].equals(obj)){
counter++;
}
}
return counter;
}
#Override
public void clear() {
for (int i=0; i < this.size(); ++i){
this.elements[i] = null;
}
this.currentSize = 0;
}
#Override
public boolean isEmpty() {
return this.size() == 0;
}
#Override
public int size() {
return this.currentSize;
}
#Override
public boolean isMember(Object obj) {
return this.count(obj) > 0;
}
#Override
public Iterator iterator() {
return new BagIterator();
}
}
the method must be implemented in the most efficient way and if possible using the methods already given in the bag adt
What I've been trying is the following:
public E MostFrequent(Bag<E> B){
for(E e : B){
int counter = B.count(e)
}
}
but I don't seem to think of a way to return the object with more frequencies inside the loop

Java Hashtable Chaining

I am supposed to write a Java Hashtable function being able to import java.util.Iterator, java.util.NoSuchElementException, and java.util.ConcurrentModificationException. There is no specific on what type of Hashing function to use. SO how do I write my getHashCode function. My code so far:
package data_structures;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import data_structures.LinkedListDS.IteratorHelper;
public class Hashtable<K,V> implements DictionaryADT<K,V> {
private int currentSize,maxSize,tableSize;
private long modCounter;
private LinkedListDS <DictionaryNode<K,V>> [] list;
class DictionaryNode<K,V> implements Comparable<DictionaryNode<K,V>> {
K key;
V value;
public DictionaryNode(K k, V v) {
key = k;
value = v;
}
public int compareTo(DictionaryNode<K,V> node) {
return ((Comparable<K>)key).compareTo((K)node.key);
}
}
public Hashtable(int n) {
currentSize = 0;
maxSize = n;
modCounter = 0;
tableSize = (int) (maxSize * 1.3f);
list = new LinkedListDS[tableSize];
for (int i=0; i < tableSize; i++)
list[i] = new LinkedListDS<DictionaryNode<K,V>>();
}
public boolean contains(K key) {
return list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null));
}
private int getHashCode(K key) {
// TODO Auto-generated method stub
return 0;
}
public boolean insert(K key, V value) {
if (isFull())
return false;
if (list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].addLast(new DictionaryNode<K,V>(key,value));
currentSize++;
modCounter++;
return true;
}
#Override
public boolean remove(K key) {
if (isEmpty())
return false;
if (!list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].remove(new DictionaryNode<K,V>(key,null));
currentSize--;
modCounter++;
return true;
}
public V getValue(K key) {
DictionaryNode<K,V> tmp = list[getHashCode(key)].find(new DictionaryNode<K,V>(key,null));
if (tmp == null)
return null;
return tmp.value;
}
#Override
public K getKey(V value) {
DictionaryNode<K,V> tmp = list[getHashCode(value)].find(new DictionaryNode<K,V>(null,value));
if (tmp == null)
return null;
return tmp.key;
}
public int size() {
return currentSize;
}
#Override
public boolean isFull() {
return currentSize == maxSize;
}
public boolean isEmpty() {
return currentSize == 0;
}
#Override
public void clear() {
currentSize = 0;
modCounter++;
for (int i=0; i<tableSize; i++)
list[i].makeEmpty();
}
public Iterator<K> keys() {
return new KeyIteratorHelper();
}
public Iterator<V> values() {
return new ValueIteratorHelper();
}
abstract class IteratorHelper<E> implements Iterator<E> {
protected DictionaryNode<K,V> [] nodes;
protected int idx;
protected long modCheck;
public IteratorHelper() {
nodes = new DictionaryNode[currentSize];
idx = 0;
int j = 0;
for (int i=0; i < tableSize; i++)
for (DictionaryNode n : list[i])
nodes[j++] = n;
nodes = (DictionaryNode<K,V>[]) ObjectSorter.quickSort(nodes);
}
public boolean hasNext() {
if (modCheck != modCounter)
throw new ConcurrentModificationException();
return idx < currentSize;
}
public abstract E next();
public void remove() {
throw new UnsupportedOperationException();
}
}
class KeyIteratorHelper<K> extends IteratorHelper<K> {
public KeyIteratorHelper() {
super();
}
public K next() {
return (K) nodes[idx++].key;
}
}
class ValueIteratorHelper<V> extends IteratorHelper<V> {
public ValueIteratorHelper() {
super();
}
public V next() {
return (V) nodes[idx++].value;
}
}
}

How to check diagonals in NQueens?

Im making the NQueens program in java but I am having trouble checking the diagonals. Right now I just go through the array in a way so it goes to the next diagonal spot but it is giving me out of bounds after going through the first possibility. Is there a different way to do this? Am i doing it wrong?
Here is the part that is giving me the array out of bounds exception
private boolean checkLowerDiag(int row, int col)
{
if(col == 0)
{
return false;
}
else
{
for(int i = row, j = col; i < myNumsQueen && j >= 0; i++, j--)
{
if(myBoard[i+1][j-1] == true) // this line is the out of bounds
{
return true;
}
}
return false;
}
}
Here is my entire code
package model;
public class NQueensModel
{
private int myNumsQueen;
public int myPossibilities=0;
private boolean[][] myBoard;
private static NQueensModel myModel = new NQueensModel(4);
public static void main (String[] args) {
System.out.println(myModel.solvePuzzle());
System.out.println(myModel.myPossibilities);
// System.out.println(myPossibilities);
}
public NQueensModel(int nQueens)
{
myNumsQueen = nQueens;
myPossibilities=0;
myBoard = new boolean[myNumsQueen][myNumsQueen];
}
public boolean solvePuzzle()
{
return this.solvePuzzle(0);
}
private boolean solvePuzzle(int ncolumn)
{
if(ncolumn>myNumsQueen-1)
{
myPossibilities++;
// return true;
}
int i;
for( i =0; i<myNumsQueen;i++)
{
if(this.isSafeMove(i, ncolumn)==true)
{
this.placeQueen(i,ncolumn);
System.out.println(i+ " " + ncolumn);
if(this.solvePuzzle(ncolumn+1)==true)
{
return true;
}
this.removeQueen(i, ncolumn);
System.out.println("remove: " + i+ " " + ncolumn);
}
}
return false;
}
private int solveCount(int count, int col)
{
for(int j = 0 ; j<col; j++){
if(myModel.solvePuzzle(j)==true){
count++;
}
else if(myModel.solvePuzzle(j)==false){
return count;
}
else
{
for(int i =0 ; i<col;i++){
count = solveCount(count, col+1);
}
return count;
}
return count;
}
return count;
}
private boolean isSafeMove(int row, int col)
{
if(this.checkLowerDiag(row, col)==true ||this.checkUpperDiag(row, col)==true ||this.checkLeft(row,col)==true)
{
return false;
}
else
{
return true;
}
}
private boolean checkUpperDiag(int row, int col)
{
if(row==0)
{
return false;
}
else
{
for(int i=row, j = col; i>=0 && j>=0; i--, j--)
{
if(myBoard[i][j]==true)
{
return true;
}
}
return false;
}
}
private boolean checkLowerDiag(int row, int col)
{
if(col==0 )
{
return false;
}
else
{
for(int i = row, j = col; i<myNumsQueen && j>=0; i++, j--)
{
if(myBoard[i+1][j-1]==true)
{
return true;
}
}
return false;
}
}
private boolean checkLeft(int row, int col)
{
if(col==0)
{
return false;
}
else
{
for(int i = col; i>=0; i--)
{
if(myBoard[row][i]==true)
{
return true;
}
}
return false;
}
}
private boolean placeQueen(int row, int col)
{
myBoard[row][col] = true;
return true;
}
private boolean removeQueen(int row, int col)
{
myBoard[row][col] = false;
return false;
}
// public String toString()
// {
//
// }
}

How to delete a specific element from a priority queue?

I have created a priority queue using the Java API and I want to remove a specific element from the priority queue at the end of the program. I know it has to do something with the comparator but I can't figure it out. Can someone help? Here's my code:
public static void main(String[] args)
{
PriorityQueue<Element> X = new PriorityQueue<Element>(100, new ElementComparator());
X.add(new Element(30, 3));
X.add(new Element(700, 4.5));
X.add(new Element(100, 6.2));
X.add(new Element(2, 8.1));
System.out.println(X.remove(new Element(100, 6.2)));
}
and here's my Element class:
private int index;
private double value;
public Element(int i, double v)
{
index = i;
value = v;
}
public int getIndex() { return index;};
public double getValue() { return value;};
public void setValue(double v) { value = v;};
And here's the comparator that I created:
public int compare(Element o1, Element o2)
{
int idx1 = o1.getIndex();
int idx2 = o2.getIndex();
if (idx1 < idx2) {
return -1;
} else if (idx1 > idx2) {
return 1;
} else {
return 0;
}
}
public boolean equals(Element o1, Element o2)
{
return o1.getIndex() == o2.getIndex();
}
I appreciate your help...
You need to define equals() and hashcode() on your Element object as such:
public class Element{
private int index;
private double value;
public Element(int i, double v)
{
index = i;
value = v;
}
public int getIndex() { return index;}
public double getValue() { return value;}
public void setValue(double v) { value = v;}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Element)) return false;
Element element = (Element) o;
if (index != element.index) return false;
return true;
}
#Override
public int hashCode() {
return index;
}
}
Defining equals() on the ElementComparator does not perform the same task.

Categories