Overriding value in heap java programming - java

I've added to my project a new data structure Heap<Integer,Integer> but the only problem I've got is that it prints me only one time the result.
If I have the input:
v=10;new(v,20);new(a,22);print(v)
at the end of execution
Heap={1->20, 2->22},
SymTable={v->1, a->2}
But what it gives me:
Heap: 1->22
SymTable: a -> 1
v -> 1
It overrides the first value.Here is the code from the controller where is the main part:
HeapAllocation crtStmt1=(HeapAllocation) crtStmt;
String varI = crtStmt1.getVarname();
Exp e = crtStmt1.getExpression();
int i=0;
Id<Object,Integer> tbl = state.getDict();
IHeap<Integer,Integer> heap1 = state.getHeap();
int value= e.eval(tbl, heap1);
heap1.put(++i, value);
if (tbl.containsKey(varI))
tbl.update(varI,i);
tbl.update(varI, i);
The problem I guess is after this line:
heap1.put(++i, value);
because for a new operation it doesn't append to the previous one, just overrides it.
Edit:
The implementation of the heap:
public class Heap<Integer,In> implements IHeap<Integer, Integer>,Serializable{
private Map<Integer, Integer> mapp;
public Heap(){
mapp = new HashMap<Integer,Integer>();
}
public void put(Integer index, Integer value){
mapp.put(index, value);
}
public void remove(Integer index){
try{
if(isEmpty())
throw new ExceptionRepo();
else
mapp.remove(index);
}catch (ExceptionRepo ex){
System.err.println("Error: Heap is empty.");
}
}
public boolean isEmpty(){
return mapp.isEmpty();
}
public Integer get(Integer index){
return mapp.get(index);
}
public boolean containsIndex(Integer index){
return mapp.containsKey(index);
}
public void update(Integer index, Integer value){
mapp.put(index, value);
}
public String toString(){
Set<Integer> all = mapp.keySet();
Object[] keysA= all.toArray();
String res="";
for(int i=0; i<mapp.size(); i++){
Integer v = mapp.get(keysA[i]);
res += keysA[i].toString() + "->" + v.toString() + "\r\n";
}
return res;
}
}
Edit2: Maybe the problem is in the eval function implementation.To be clear, I have a Exp class:
public class Exp{
public int eval(Id<Object,Integer> tbl)throws ExceptionRepo{
return 0;
}
public String toString(){
return "";
}
public int eval(Id<Object,Integer> tbl,IHeap<Integer,Integer> heap) throws ExceptionRepo{
return 0;
}
And some derived classes that extends the Exp class.I added a new method in the ConstExp class:
public class ConstExp extends Exp implements Serializable{
int number;
public int eval(Id<Object,Integer> tbl) throws ExceptionRepo{
return number;
}
public ConstExp(int n){
number = n;
}
public String toString(){
return "" + number;
}
public int eval(Id<Object,Integer> tbl,IHeap<Integer,Integer> heap) throws ExceptionRepo{
return number; //THIS IS THE NEW METHOD
}
This class should return a value..so for "v=20", after execution of the statement it puts the value 20 in the v based on this class implementation.
If it's useful this is the statement evaluation rule for the heap(that I implemented in the controller up there):
Stack1={new(var,exp)| Stmt2|...}
SymTable1
Heap1
==>
Stack2={Stmt2|...}
let be v=eval(exp,SymTable1,Heap1) in
Heap2 = Heap1 U {newfreelocation ->v}
if var exists in SymTable1 then SymTable2 = update(SymTable1,
var,newfreelocation)
else SymTable2 = add(SymTable1,var, newfreelocation)
How to resolve this?

Related

Creating Objects of a Class in Java that declares an array of object, but only one of them will print

The goal of my program is to store data for students(First Name, Last Name, ID#).I'm trying to create 4 Arrays. One array will hold the combined value of each student object that I'm adding(myDB). The other 3 hold indexes to the original spot of each value(Fname,Lname,ID) and add them to an ordered array without sorting the array. The trouble I'm having is that once I add something to the Index Arrays and go to print them, it prints all of the IDs regardless of what object I call.
//class containing methods to list, add, and delete
//Class that declares the main database array that holds all three (ID,First,Last)
import java.io.FileInputStream;
import java.util.*;
public class DataBase
{
private String tempID, tempFname, tempLname;
private DataBaseArray myDB;
private int nextDBRecord;
private IndexArray ID;
private IndexArray First;
private IndexArray Last;
public DataBase()
{
nextDBRecord = 0;
myDB =new DataBaseArray(100);
ID=(new IndexArray(100));
First=new IndexArray(100);
Last=new IndexArray(100);
}
void addData(String last, String first, String id)
{
tempLname = new String(last);
tempFname = new String(first);
tempID = new String(id);
//ID.insert(new IndexRecord(tempID, nextDBRecord));
First.insert(new IndexRecord(tempFname,nextDBRecord));
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));
System.out.println(myDB.getStudentArray()[nextDBRecord]);
nextDBRecord++;
}
void addIt ()
{
Scanner keyb = new Scanner(System.in);
System.out.println("Please enter the ID for new student entry");
tempID=keyb.next();
ID.insert(new IndexRecord(tempID, nextDBRecord));
System.out.println("Please enter the first name of the new student");
tempFname=keyb.next();
First.insert(new IndexRecord(tempFname, nextDBRecord));
System.out.println("Please eneter the last name of the new student");
tempLname=keyb.next();
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));;
nextDBRecord++;
}
void findIt()
{
}
void list (int type, int order)
{
First.printIt(order);
}
}
//Class that creates the objects to add to Iarray Farray Iarray
//IndexArray is a static array
//Creates a single entry into the IndexArray
//Need a compareTo method that gives the where value of each object
public class IndexRecord
{
private String key; //Value
private int where; //Where it is at in DataBaseArray
IndexRecord (String value, int position)
{
setKey(new String(value));
where = position;
}
public String toString()
{
return getKey()+" "+ String.valueOf(where);
}
public String getKey() //Getter for key value of the new student that is being added
{
return key;
}
public void setKey(String key) //Setter for key value of the new student that is being added
{
this.key = key;
}
}
//Same as OrderedArray Class
//Add Iterator methods. Instead of printing here, tell DataBase class what DatabaseRecord objects to print
public class IndexArray
{
private static IndexRecord[] irArray;
private int nOfElem; //Should be the same for each array so only 1 counter is needed
private int maxSize;
private int theIterator;
public IndexArray(int size)
{
nOfElem = 0;
maxSize=size;
irArray = new IndexRecord[size];
}
//-----------------------------Getters and Setters-------------------------------------
public int size() //Getter to find num of elements in array that can be called in other class
{ return nOfElem; }
public IndexRecord[] getIRarray()
{
return irArray;
}
//---------------------Iterator Methods-----------------------------------------------------
void iteratorToFront()
{
theIterator=(nOfElem>0? 0 : -1);
}
void iteratorToBack()
{
theIterator=(nOfElem>0 ? nOfElem-1 : -1);
}
boolean hasNext()
{
return (theIterator==nOfElem-1? false:true );
}
boolean hasPrevious()
{
return (theIterator==0? false : true);
}
public IndexRecord getIterator()
{
return(theIterator==-1 ? null :irArray[theIterator]);
}
int getNext()
{
theIterator=(hasNext()? theIterator+1: -1);
return(theIterator==-1? null : theIterator);
}
int getPrevious()
{
theIterator=(hasPrevious()? theIterator-1:-1);
return (theIterator==-1? null : theIterator);
}
//------------------Methods Called In Main---------------------------------------
public boolean insert(IndexRecord ir)
{
if(maxSize==nOfElem) return false;
int j;
for(j=nOfElem-1;j>=0;j--)
{
if(irArray[j].getKey().compareToIgnoreCase(ir.getKey())<0)break;
{
irArray[j+1]=irArray[j]; //Pushes all objects down to make room for new one
}
}
irArray[j+1]=ir;
nOfElem++;
return true;
}
public int find(String searchKey)
{
int lowerBound = 0;
int upperBound = nOfElem-1;
int currentRef;
while(true)
{
currentRef = (lowerBound + upperBound) / 2;
String tempValue = String.valueOf(irArray[currentRef].getKey());
if(tempValue.compareTo(searchKey) == 0)
return currentRef;
else if (lowerBound > upperBound)
return nOfElem; //returns a pointer to an empty slot
else
{
if(tempValue.compareTo(searchKey) > 0)
lowerBound = currentRef++;
else
upperBound = currentRef - 1;
}
}
}
//delete
public void printIt(int order)
{
switch(order)
{
case -1:
iteratorToBack();
break;
case 1:
iteratorToFront();
while(hasNext())
{
System.out.println(irArray[getNext()]);
}
break;
default:
}
}
}

Java: How to populate a variable in subclass?

So this is not a assignment but one of my lecture slide did not make it clear and when I try to code something similar myself, I run into a problem.
I can't figure out how to populate a variable that is in my subclass.
here's my test code thus far:
Implementation class:
import javax.swing.JOptionPane;
public class House {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int count = 0;
room[] r = new room[3];
int option = JOptionPane.showConfirmDialog(null, "type");
if(option==0){
r[count]=new type();
r[count].setSize(25);
r[count].setType("Bedroom");
}
else if(option==1){
r[count] = new room();
r[count].setSize(25);
}
JOptionPane.showMessageDialog(null, r[count].toString());
}
}
Superclass:
public class room {
double size;
public room(){
}
public room(double size){
this.size=size;
}
public double getSize(){return this.size;}
public boolean setSize(double size){
if(size<0.0){
return false;
}
else{
return true;
}
}
public String toString(){
return "Room size: " + this.size;
}
}
Subclass:
public class type extends room {
String type;
public type(){
}
public type (double size, String type){
super(size);
this.type=type;
}
public String getType(){return this.type;}
public boolean setType (String type){
if(type.equals("")){
return false;
}
else{
return true;
}
}
public String toString(){
return super.toString() + "Room Type: " + this.getType();
}
}
when i try to run the code, if I tried to insert data into setType() method in type class, it would give me an error. Can someone please tell me where I am messing up? Thanks!
Remember the original pointer:
if(option==0){
type t = new type();
t.setSize(25);
t.setType("Bedroom");
r[count]= t;
}
Alternatively you can cast to original type:
((type) r[count]).setType("Bedroom");

Call method through Arraylist of another class containing a HashMap

So I'm taking a basic course in Java at university. I'm trying to create a class Bachelorstudents containing an arraylist of class Bachelorstudent (respectively plural and singular of "bachelorstudents" in english) which contains a HashMap of course (key) and marks (value).
My problem is the infamous "non-static method cannot be referenced from a static context".
"Bachelorstudent"-class:
public class Bachelorstudent{
private String navn;
private int studentNummer;
private HashMap<String, Integer> karakterListe = new HashMap<>();
public Bachelorstudent(String navn, Integer studentNummer){
setNavn(navn);
setStudentNummer(studentNummer);
}
public Bachelorstudent(){
}
public void setKarakter(String fagkode, Integer karakter){
karakterListe.put(fagkode, karakter);
}
public HashMap<String, Integer> getKarakter(){
return karakterListe;
}
public int snitt(){
Integer snittKarakter = 0;
int counter = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
snittKarakter += karakter;
counter++;
}
}else{
return 6;
}
return snittKarakter /= counter;
}
public int getKarakterer(){
Integer karakterer = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
karakterer += karakter;
}
}else{
return 0;
}
return karakterer;
}
public void setNavn(String navn){
this.navn=navn;
}
public String getNavn(){
return navn;
}
public void setStudentNummer(int studentNummber){
this.studentNummer=studentNummer;
}
public int getStudentNummer(){
return studentNummer;
}
}
"Bachelorstudenter"-class:
public class Bachelorstudenter{
private ArrayList<Bachelorstudent> bachelorStudenter = new ArrayList<>();
public Bachelorstudenter(){
}
public void karakterSnitt(){
for(Bachelorstudent bachelorstudenter : bachelorStudenter){
Bachelorstudent student = new Bachelorstudent();
for(Bachelorstudent bachelorstudent : Bachelorstudent.getKarakter()){ //<-- Non-static method error.
}
}
}
public Boolean eksisterer(Bachelorstudent student){
boolean finnes = false;
for(Bachelorstudent bachelorstudent : bachelorStudenter){
if(bachelorstudent.getNavn().equals(student.getNavn())){
finnes = true;
}
}
return finnes;
}
public Boolean nyBachelorstudent(Bachelorstudent student){
if(!eksisterer(student)){
bachelorStudenter.add(student);
return true;
}
else{
System.out.println("Eksisterer i systemet fra før");
return false;
}
}
}
I have tried several things, such as calling an instance of class Bachelorstudent (as seen above), tried inheritance (not sure if I did this right, but what I did didn't work). How can I call on the .getKarakter() method in class Bachelorstudenter?
Edit: Just to clarify. The point of this method is to get the average of every mark of every bachelorstudent. I have a method in Bachelorstudent which does this, but I need the equivalent in Bachelorstudenter, which will find the average of every mark of every course of every student.
You need to use an object to call a non-static method.
In your example, you need to use the object of the current iteration to invoke the method:
for(Bachelorstudent bachelorstudenter : bachelorStudenter){ // Iterate over the bachelorStudenter list.
bachelorstudenter.getKarakter(); // Use the bachelorstudenter of this iteration.
}

Number of instances counter subclass

Eclipse keeps informing of an error when I try to implement a counter for a number of instances when called by the constructor. I've been searching on the matter, but the solutions are the exact thing eclipse won't let.
The problem is in Student() { count++; } in the subclass.
Implicit super constructor Dosije() is undefined. Must explicitly invoke another constructor
Main file
import java.util.Scanner;
public class TestDosije {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String jmbg=null;
System.out.println("ime osobe: ");
String ime= in.next();
System.out.println("prezime osobe: ");
String prezime= in.next();
System.out.println("jmbg: ");
while(!(Dosije.jesteJMBG(jmbg =in.next()) )) {
}
String ime_prezime= ime + " " + prezime;
Dosije dosije = new Dosije(ime_prezime, jmbg);
System.out.println(dosije.toString());
System.out.println("broj indeksa: ");
int index= in.nextInt();
System.out.println("godina upisa: ");
int upis= in.nextInt();
System.out.println("studije: ");
int studije= in.nextInt();
Student student = new Student(dosije, index, upis, studije);
System.out.println(student.toString());
System.out.println(student.getCount());
}
}
The superclass
public class Dosije {
private String ime_prezime;
private String jmbg;
public Dosije(String ime_prezime, String jmbg) {
this.ime_prezime=ime_prezime;
this.jmbg=jmbg;
}
public Dosije(final Dosije d) {
ime_prezime=d.ime_prezime;
jmbg=d.jmbg;
}
public String getImePrezime() { return ime_prezime; }
public void setImePrezime(String ime_prezime) { this.ime_prezime= ime_prezime;}
public String getJMBG() { return jmbg; }
public void setJMBG(String jmbg) { this.jmbg= jmbg;}
public String toString() {
return ime_prezime + "\njmbg: " + jmbg;
}
public static boolean jesteJMBG(String jmbg) {
if(jmbg.length() != 13) {
System.err.println("jmbg ima 13 cifara");
return false;
}
for(int i=0;i < jmbg.length(); i++) {
if(!(Character.isDigit(jmbg.charAt(i))) ) {
System.err.println("jmbg nije broj!");
return false;
}
}
return true;
}
}
The subclass of which instances I'm trying to count
public class Student extends Dosije{
private int br_index;
private int god_upis;
private int profil_studija;
private static int count=0;
Student() {
count++; //the devil himself
}
public Student(final Dosije d, int index, int upis, int studije){
super(d);
br_index=index;
god_upis=upis;
profil_studija=studije;
}
public Student(final Student s) {
super(s);
br_index=s.br_index;
god_upis=s.god_upis;
profil_studija=s.profil_studija;
}
public void setProfil(int n) {profil_studija=n;}
public int getCount() { return count; }
public String Studije(int i) {
if(i == 0)
return "Osnovne";
else if(i == 1)
return "MSc";
else
return "PhD";
}
public String toString() {
return super.toString() + "\n" + "broj indeksa: " + br_index + "/" + (god_upis % 100) + "\n"
+ "studije: " + Studije(profil_studija);
}
}
Your Student() constructor doesn't pass compilation since the super class doesn't have a parameterless constructor, so the implicit call to super(); added by the compiler doesn't pass compilation.
You can add a public Dosije() {} constructor to prevent that compilation error.
However, you might want to increment count in the other Student constructors too, in order to count the total number of instances created, regardless of which constructor was used.

Making this template class into a generic class

So I am a college student just looking for a little help and understanding, I have a professor that does not allow us to use java pre-written classes such as ArrayList, so I am trying to figure out how to modify my current encapsulated array class to use generics so that I don't have to do so much casting in the application class of my program
public class ArrayClass {
private Object[] objArray;
private int index = 0;
public static final int MAX_SIZE = 100;
public ArrayClass(){
objArray = new Object[100];
}
public ArrayClass(int numSlots){
objArray = new Object[numSlots];
}
public ArrayClass(Object[] anArray, int newIndex){
objArray = new Object[newIndex];
for(int i=0; i<newIndex; i++){
objArray[i] = anArray[i];
}
index = newIndex;
}
//return object array, accessor
public Object[] getstrArr(){
return objArray;
}
//return # of actual data in array, accessor
public int getIndex(){
return index;
}
//return an object at given pos, accesor
public Object getObject(int pos){
return objArray[pos];
}
//assign a new object array, mutator
public void setObjArr(Object[] aStrArr){
for(int i=0; i<index; i++){
objArray[i] = aStrArr[i];
}
}
//assign a new index, mutator
public void setIndex(int anIndex){
index = anIndex;
}
//insert a new string into the array if there is room, increment index
public void add(Object someObj){
if(index < objArray.length){
objArray[index] = someObj;
index++;
}
}
//return the string with contents of array
public String toString(){
String output = " ";
for(int i=0; i<index; i++){
output = output + objArray[i].toString();
}
return output;
}
//return true if calling object is equivalent to argument
public boolean equals(Object someObj){
for(int i=0; i< index; i++){
if(objArray[i].equals(someObj))
return true;
}
return false;
}
}
public class ArrayClass<E> {
// return object array, accessor
public <T> T[] getstrArr(T[] t) {<--This is done because arrays are covarant in nature
return (T[]) Arrays.copyOf(objArray, index, t.getClass());
}
// return an object at given pos, accesor
public E getObject(int pos) {<-- For single elements just return E with casting
return (E) objArray[pos];
}
Implementation Notes
Length checks should be considered for Arrays.copy of
You can read a nice article about generics
Well, i would not expose your index with methods like setIndex, etc. Not adding null element check too.
Anyway, I would make something like:
public class ArrayClass<E> {
...
private E[] elements;
private int index;
...
public ArrayClass() {
this.elements = (E[]) new Object[MAX_SIZE];
this.index = 0;
}
// this constructor substitutes the method setObjArr
public ArrayClass(E[] elements) {
this.elements = elements;
this.index = elements.length;
}
...
public void add(E element) {
if (needsToGrow()) {
duplicateArraySize();
}
this.elements[index++] = element;
}
private boolean needsToGrow() {
return index + 1 == elements.length;
}
private void duplicateArraySize() {
E[] extendedArray = (E[]) new Object[this.elements.length * 2];
System.arraycopy(elements, 0, extendedArray, 0, elements.length);
this.elements = extendedArray;
}
public E get(int index) {
return this.elements[index];
}
public int size() {
return this.index;
}
...
}
I would do it like that:
public class ArrayClass<T> {
public T[] objArray;
private int index = 0;
public static final int MAX_SIZE = 100;
#SuppressWarnings("unchecked")
public ArrayClass(Class<T> c) {
objArray = (T[]) Array.newInstance(c,MAX_SIZE);
}
}
and so on.
And then:
ArrayClass<String> myStringArray = new ArrayClass<String>(String.class);

Categories