Changing an array using a method inside a class - java

I tried a lot to fix this class but it didn't work. I want to make a hotel(Array) and check and fill it with people defined in another class, but I need to add ,remove, check for empty items and return their indexes using methods inside the hotel class. the problem is when I change the array inside a method I couldn't return the changed value and when I tried adding other class members trying to work it out I ended with indexOutOfboundryException. Could you pleas take a look at the code and tell me if you see the mistakes why I couldn't return the changed value and why I get index out of boundry
Many thanks in advance!
package com.company;
public class Hotel1 {
private int numberOfRooms1; // Number of rooms
private Person[]bookingList1=new Person[numberOfRooms1];// booking list with initial length of the number of rooms
private int uniqueId1;
private Person person1;
private int currentIndex;
private boolean isEmpty=true;
public int getNumberOfRooms1() {
return numberOfRooms1;
}
private Ticket ticket1;
public Hotel1(int numberOfRoomss1) {// The constructor has one attribute which is the number of the rooms
this.numberOfRooms1 = numberOfRoomss1;
}
//check in method
public Boolean isEmpty(){
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
if (!bookingList1[currentIndex].equals(null))
isEmpty=false;
else isEmpty= true;
}
return isEmpty;
}
public int findEmptyRooms(){
if (isEmpty)
{
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
return currentIndex;
}
return currentIndex;
}
return currentIndex;
}
public Person checkIn1(Person person){
if (isEmpty==true){
return bookingList1[findEmptyRooms()]=person;
}
else {
System.out.println("There is no empty rooms");
return null;
}
}
}

Aarrghh so many bugs in few lines...
Sorry to be rude but please review the logic of your code, i don't all understand...
For example :
public int findEmptyRooms(){
if (isEmpty)
{
for (currentIndex=0;currentIndex
}
What this function is supposed to do ?!
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
return currentIndex;
}
Simply always retuns bookingList1.length + 1
(so that's why the call to checkIn1 throws an indexOutOfboundryException)
Another example :
public Boolean isEmpty(){
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
if (!bookingList1[currentIndex].equals(null))
isEmpty=false;
else isEmpty= true;
}
return isEmpty;
}
Is completely buggy, if you have an element in the array with null followed by non null elements, the isEmpty will returns false
I think you should reconsider all your code before posting the question to stack overflow

Thank you all for your answers that help me refactor the whole code and make it better and get it work just in case you want to see how it became just take a look`package com.company;
public class Hotel1 {
private int numberOfRooms1;// number of rooms
Person rooms[];
public Hotel1(int numberOfRooms1){ //the constructor
this.numberOfRooms1=numberOfRooms1;
Person[]rooms=new Person[numberOfRooms1];
this.rooms=rooms;
}
//Private method to check if the array has an empty place
private boolean isEmpty(){
boolean isEmpty =false;
for (int i=0;i<rooms.length;i++){
if (rooms[i]==null){
return true;
}
}
return isEmpty;
}
//Check in
public Person[] checkIn(Person person){
if (isEmpty()){
for (int i=0;i<rooms.length;i++){
if (rooms[i]==null){
rooms[i]=person;
return rooms;
}
else continue;
}
}
else {
System.out.println("There is rooms left for "+person.getFirstName()+" Sorry!");
}
return rooms;
}}

Related

incompatible return type using multiple classes

Im writing a program to simulate simple queues of Process Control Blocks and having an issue with a return value in my returnPcb() method. I am getting an "invalid return type". I know the return type in my method is a Pcb, but I cannot change it. I want to return the value of -1 if the the call to removePcb() is false. My thought was to create a new Pcb, set a value to -1, and return that value. This is where I am running into issues. I need help returning -1 when the condition is false. Thank you.
MasterQueue Class:
import java.util.*;
public class MasterQueue {
HashMap<String,Queue<Pcb>>hash;
MasterQueue(){
hash = new HashMap<>();
}
public boolean addQueue(String nameIn){
String QueueName = nameIn;
if(hash.containsKey(QueueName)){
return false;
}
//else add new queue the hashmap
else{
Queue<Pcb> q = new LinkedList<>();
hash.put(QueueName,q);
return true;
}
}
public boolean addPcb(Pcb p,String nameIn){
String PcbName = nameIn;
//if queue exist in the list then add the pcb to it
if(hash.containsKey(PcbName)){
hash.get(PcbName).add(p);
return true;
}
//else return false
else{
return false;
}
}
public Pcb removePcb(String nameIn){
String RemovePcbName = nameIn;
//if this queue exist in the list then remove first element from the queue
if(hash.containsKey(RemovePcbName)){
return hash.get(RemovePcbName).remove();
}
Pcb p = new Pcb(0, 0, 0, -1);
return p.getPid();
}
}
PCB Class:
public class Pcb {
private int low;
private int high;
private int state;
int pid;
Pcb(int lowMemIn, int highMemIn, int stateIn, int pidIn){
setLowMem(lowMemIn);
setHighMem(highMemIn);
setState(stateIn);
setPid(pidIn);
}
public void setLowMem(int lowMemIn){
low = lowMemIn;
}
public int getLowMem(){
return low;
}
public void setHighMem(int highMemIn) {
high = highMemIn;
}
public int getHighMem(){
return high;
}
public void setState(int stateIn){
state = stateIn;
}
public int getState() {
return state;
}
public void setPid(int pidIn){
pid = pidIn;
}
public int getPid(){
return pid;
}
}
Test
#Test
public void testAddPcb1() {
Pcb pid1 = new Pcb(1, 2, 3, 4);
MasterQueue mq1 = new MasterQueue();
mq1.addQueue("miniQueueStr");
Assert.assertTrue("error", mq1.addPcb(pid1, "miniQueueStr"));
Your method is currently defined as:
public Pcb removePcb(String nameIn){
String RemovePcbName = nameIn;
//if this queue exist in the list then remove first element from the queue
if(hash.containsKey(RemovePcbName)){
return hash.get(RemovePcbName).remove();
}
Pcb p = new Pcb(0, 0, 0, -1);
return p.getPid();
}
so you promised the compiler that this code would be returning a Pcb object, and nothing else. You can't just decide to make it return something else instead, it has to be a Pcb object.
So do that: you define that failcase Pcb p = Pcb(0,0,0,-1) so just return that p at the end of the function and the compiler will be happy.
However, if there is no matching Pcb, you really shouldn't be returning a Pcb object that happens to be set to values that you assume have meaning without formally declaring it as some constant, at which point things get silly... What you probably want to do instead is make your function throw:
public Pcb removePcb(String nameIn) throws NoSuchElementException {
String RemovePcbName = nameIn;
//if this queue exist in the list then remove first element from the queue
if(hash.containsKey(RemovePcbName)){
return hash.get(RemovePcbName).remove();
}
throw new NoSuchElementException();
}
And then in your consuming code, put that removal call inside a try/catch and do what you as programmer know needs to happen when someone tries to remove a Pcb that doesn't exist.

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.
}

Java inheritance ( local variable/ boolean in if)

I am studying the inheritance (Java), and I wrote the following code. The first part is the CarBase, and then I created a childclass 1, called Bus.
My idea is that first make a judgement if it is a bus, and by doing that, I need a boolean [if(isBus)], but when I wrote this code in Eclipse, there is a error message, said 'isBus can not be resolved to a variable'.
Could some one please tell me how to solve this problem? Do I need to declare the boolean variable first?
Another question is about the declaration of local variables.
In the getOnBus(0 method, I have a local variable called temp,I was taught that whenever using a local variable insided a method, I need to declare it first and then I shall be able to use it, but I saw someone use it directly like the following, I was wandering what's the difference between the two?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus(int p_amount) {
if(isBus) {
int temp = 0; // <===
temp = current_Passenger + p_amount; // <===
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
or if there is difference if I use it without declaring it?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if(isBus) {
int temp=current_Passenger+p_amount; // <====
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The code is as following
First Part CarBase(parent)
public class CarBase {
public int speed;
public String name;
public String color;
public int maxSpeed = 90;
// Method
public void speedUp(int p_speed) {
int tempSpeed = 0;
if (p_speed > 0) {
tempSpeed = speed + p_speed;
}
if (tempSpeed <= maxSpeed) {
speed =tempSpeed;
}
}
}
Second Part Bus (Child1)
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if (isBus) {
int temp = 0;
temp = current_Passenger + p_amount;
if (temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The point in using inherance is to abstract whether an object is a Car or a Bus, and write code that works no matter what is passed. To do so, you use abstract methods. Consider
abstract class Vehicle {
private int occupied;
public Vehicle() {
occupied = 0;
}
public abstract int getCapacity(); // number of passengers
public boolean board(int howmany) {
if (occupied+howmany <= capacity) {
occupied += howmany;
return true;
}
else
return false;
}
public void unboard(int howmany) {
occupied -= howmany;
}
};
class Car extends Vehicle {
public Car () { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 5; }
}
class Bus extends Vehicle {
public Bus() { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 32; }
}
you'd write every function to accept a Vehicle, and deal with it without the need to know if it is a bus or a car. (the following is a dumb function, just to give you an example)
void board_on_first_avaible(Vehicle[] x, int n) {
for (int i=0; i<x.length; x++)
if (x.board(n))
return true; // board ok
return false; // couldn't board on anything
}
Note that you should design your code so that the functions are declared, abstract in Vehicle, for both Car and Bus. Thus getOnBus() would be a bad idea
OK for the first point "isBus" is not declared, i can not see the point of checking in this method as you already know u are extending the CarBase but if you need to check you can do it like this
if(this instanceof CarBase)
for the second point there is actually no effect for the change
int temp=0; // <===
temp= current_Passenger+p_amount; // <===
first you initialize with 0 then you assign the new value to it
int temp=current_Passenger+p_amount;
here you initialize the temp with the value
You don't need to check if the Bus object 'isBus()' .... it IS a Bus, because you are defining the class as Bus!
So... if you were to create a new Bus object, you would say something like:
Bus BigYellowBus0001 = new Bus();
if you were to then say:
BigYellowBus0001.getOnBus(10);
You would NOT need to check if BigYellowBus0001 is a bus.... right?
In fact, you don't even need to name the method getOnBus().... it could just be getOn.
I think maybe you've gotten off on the wrong foot by deciding that Bus is a subclass of Car.
As for local variables, this just means variable that begin and end inside the method... so you did that nicely with your 'temp' variable.
To show that you understand how to access variables of the superclass from the child class, you could check the speed of the bus before letting people on:
public boolean getOnBus (int p_amount){
if(speed = 0){
int temp=0;
temp= current_Passenger+p_amount;
if( temp > max_Passenger){
return false;
} else{
current_Passenger = temp;
return true;
}
}
return false;
}
isBus is not declared that reason why you got this error
You doesn't need this check, because this method declared for Bus class and you are sure what it IS a Bus not a parent CarBase class (please use Vechicle instead of CarBase, it's much better on my opinion)
In Java 0 is default value for int, so you don't need to init variable before assign new value
So you can simplify getOnBus() like that
public boolean getOnBus (int p_amount) {
int temp = current_Passenger + p_amount;
if (temp > max_Passenger) return false;
current_Passenger = temp;
return true;
}
To test if an object is an instance of a class you can to use variable instanceof YourClass which evaluates to a boolean

Returning arraylist error

I've been trying to create a class which determines if a set of integers within an arraylist is a subset of another arraylist.
However, I receive an "error: incompatible types: ArrayList cannot be converted to int" whenever I try to compile and it appears that "return members" is causing it.
Could someone tell me what is wrong with "return members"? Any help would be greatly appreciated.
// Define the Set class
import java.util.ArrayList;
class Set {
private ArrayList<Integer> members;
public Set()
{
members = new ArrayList<Integer>();
}
public int getMembers()
{
return members;
}
public void setMembers()
{
this.members = members;
}
// toString() method
public String toString()
{
return "Set A is a subset of set B.";
}
// Return true if 'this' is a subset of 'set',
// otherwise return false.
public boolean isSubset(Set set)
{
for(int i = 0; i < this.members.size(); i++)
if(!members.contains(this.members.get(i)))
return false;
return true;
}
}
This method is your issue:
public int getMembers()
{
return members;
}
Wrong return type, change it to:
public ArrayList<Integer> getMembers()
{
return members;
}
Also your setMembers() does not do anything, set's itself to itself. It should be changed to:
public void setMembers(ArrayList<Integer> newMembers)
{
this.members = newMembers;
}
you are making mistake in first place.change return type in getMenbers(). you are returning an Object type and you specified it to return an int(primitive).
a typical method can only return the specified type. hope it helps

I have the methods, but need program code for Grade enum

I need to write a Java enumeration LetterGrade that represents letter grades A through F, including plus and minus grades.
Now this is my enumeration code:
public enum Grade {
A(true),
A_PLUS(true),
A_MINUS(true),
B(true),
B_PLUS(true),
B_MINUS(true),
C(true),
D(true),
E(true),
F(false);
final private boolean passed;
private Grade(boolean passed) {
this.passed = passed;
}
public boolean isPassing() {
return this.passed;
}
#Override
public String toString() {
final String name = name();
if (name.contains("PLUS")) {
return name.charAt(0) + "+";
}
else if (name.contains("MINUS")) {
return name.charAt(0) + "-";
}
else {
return name;
}
}
What I am confused about is writing the main program. I think it could be quite straightforward but I have no clue on how to start it.
I don't want the whole code. Just a few lines to give me a head start. The rest I will try to figure out on my own.
I imagine you have a Student class that looks like this:
class Student {
protected Grade grade = null;
public Student(Grade g) {
this.grade = g;
}
}
Then you simply add a method in this class calling the isPassing method from your enum:
public boolean isPassing() {
if (this.grade != null)
return this.grade.isPassing();
return false;
}
This is supposing the passed boolean in Grade are correctly set and are invariant.

Categories