Can compare user input(scanner) and arrayList from Calendar? - java

I wanted to get only the available date not from the arrayList(Rental) but for arrayList(Resort). Unfortunately, I was unable to compare both and the output that I get from are the arrayList(Rental).
public static void listavailableResort(ArrayList resortList, ArrayList rentalList)
{
Resort rt;
Rental rl;
Person p;
boolean availresort = false;
boolean availrental = false;
//viewing available resortList from rentalList
for (int i = 0; i<resortList.size();i++)
{
availresort = true;
rt =(Resort)resortList.get(i);
for (int k = 0; k< rentalList.size();k++)
{
availrental = true;
rl = (Rental)rentalList.get(k);
//Compare between the user entered and the rentalList
//start is arrivaldate end is departuredate
if(((!(start.equals(rl.getarrivalDate())))&&(!(end.equals(rl.getDepartureDate()))))||((start.before(rl.getarrivalDate()))&&(end.before(rl.getDepartureDate()))) || ((start.after(rl.getarrivalDate())))&&(end.after(rl.getDepartureDate())))
{
rt = rl.getresort();
if (rt instanceof Chalet)
{
//how to check if two date are equals
Chalet t = (Chalet)rt;
System.out.println((i+1)+"\t"+t.getresortID()+"\t"+t.getblock()+"\t"+t.getunitNumber());
}
else if(rt instanceof Bungalow)
{
Bungalow b =(Bungalow)rt;
System.out.println((i+1)+"\t"+b.getresortID()+"\t\t"+b.getblock()+"\t\t\t\t"+b.getwifi()+"\t\t "+b.getrate());
}
}
else
{
if (rt instanceof Chalet)
{
//how to check if two date are equals
Chalet t = (Chalet)rt;
System.out.println((i+1)+"\t"+t.getresortID()+"\t"+t.getblock()+"\t"+t.getunitNumber());
}
else if(rt instanceof Bungalow)
{
Bungalow b =(Bungalow)rt;
System.out.println((i+1)+"\t"+b.getresortID()+"\t\t"+b.getblock()+"\t\t\t\t"+b.getwifi()+"\t\t "+b.getrate());
}
}
}
I apologize if the coding is messy... I just need to know how to compare the input(Scanner) and the arrayList(getting from the rentalList(arrivalDate and departuredate))
Many thks

Related

Method that doesn't allow more participants than the maximum and same number of registration

I have a issue here. I need to create this method:
Method: registraParticipante (Aluno alu) that will receive by parameter one
student(Aluno) and add to the participant(participante) array. The method should also implement the following rules:
control not to allow more participants to register which was defined in the attribute: Maximum number of participants(qtMaxParticipantes);
not allow registration of a participant who has the same number of registration(int matricula) of an already registered participant.
I have the superclass Usuario (means User) with the int matricula in it
and the subclass Aluno (means student)
PROBLEM SOLVED - Thanks Andre.
public void registraParticipante(Aluno alu) {
if (!matriculaJaExistente(alu))
{
for (int i = 0; i < listaDeParticipantes.length; i++)
{
if (listaDeParticipantes[i] == null)
{
listaDeParticipantes[i] = alu;
break;
} else {
System.out.println("Número maximo de participante atingido.");
}
}
} else {
System.out.println("Aluno já matriculado.");
}
}
public boolean matriculaJaExistente(Aluno a)
{
boolean resultado = false;
for (int i = 0; i < listaDeParticipantes.length; i++)
{if (listaDeParticipantes[i].getMatricula() == a.getMatricula())
{
resultado = true;
}
else
{
resultado = false;
}
}
return resultado ;
}
I don't know if you necessarily have to use an array, so I guess that using a List would be the best solution, than, your code would look like this:
List<Aluno> alunosList = new ArrayList();
private int maxParticipantes = 5; // arbitrary number
public void registraParticipante(Aluno a) {
if (alunosList.size() > maxParticipantes || alunoJaRegistrado(a)) {
System.out.println("Can't add this aluno");
} else {
alunosList.add(a);
}
}
public boolean alunoJaRegistrado(Aluno aluno) {
boolean result;
for (Aluno a : alunosList) { // this goes through each aluno on the list
if (a.getMatricula() == aluno.getMatricula) {
result = true;
break;
} else result = false;
}
return result;
}

Get random object from arraylist specific variable

I'm trying to get a random object from an arraylist. The random should be among the object in the arraylist having the variable available as true.
Right now it get a random attendant from the whole arraylist. I just need it to specify a limit to attendants being true(variable)
this is the line:
return myAtt.get(randAtt.nextInt(myAtt.size()));
This is the method:
public static Attendant askForAtt() {
Scanner scanAtt = new Scanner(System.in);
Random randAtt = new Random();
//Attendant asnAtt = null;
System.out.println("Do you require an Attendant ? Y or N");
String response = scanAtt.next();
if ((response.equals("y")) || (response.equals("yes")) || (response.equals("Yes")) || (response.equals("Y"))) {
// Cars.setAssignedTo(myAtt.get(randAtt.nextInt(myAtt.size())));
return myAtt.get(randAtt.nextInt(myAtt.size()));
} else if ((response.equals("n")) || (response.equals("no")) || (response.equals("No")) || (response.equals("N"))) {
return new Attendant ("User");
}
return new Attendant ("User"); //If input is neither Yes nor No then return new Attendant
}
What am I supposed to type?
My attendants are like that:
public Attendant(int staffNum, String id, boolean available, attNm name, Cars assign) {
this.staffNum = staffNum;
this.id = id;
this.available = available;
this.name = name;
this.assign = assign;
}
PS:Sorry for my English. It's my 3rd language
On your Attendant class, add this function
public boolean isAvailable(){
return available;
}
Then
public static Attendant askForAtt() {
...
if ((response.equals("y")) || (response.equals("yes")) || (response.equals("Yes")) || (response.equals("Y")) && someoneIsAvailable()) {
ArrayList<Attendant> temp = getAvailableAttendants();
Attendant attendant = temp.get(randAtt.nextInt(temp.size()));
return attendant;
}
...
}
public boolean someoneIsAvailable(){
for(int i = 0; i<myAtt.size(); i++){
if(myAtt.get(i).isAvailable()){
return true;
}
}
return false;
}
public ArrayList<Attendant> getAvailableAttendants(){
ArrayList<Attendant> availableAtt = new ArrayList<>();
for(int i = 0; i<myAtt.size(); i++){
Attendant att = myAtt.get(i)
if(att.isAvailable()){
availableAtt.add(att);
}
}
return availableAtt;
}
Also, you can use
String.equalsIgnoreCase(String);
cause in your trapping the user could do "yEs". Hope that helps. Tell me if something is wrong

"Duplicate" entries in ArrayList?

i have this class thats going to fill a list with All employees that are pre made in an array. I can populate an ArrayList with employees but the only problem is that i get a few "Duplicate" entries, i use quotes cause they are not EXACTLY the same but they could share the same name or employee number but may not have the same hire year or salary ect.
heres the employee class :
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Empnum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C",
"0321-A", "0312-B","1234-D","4321-C","1122-D"};
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart",
"Dave","Benjamin","Dan","Brian","Michelle"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
public String toString(){
String data = "\n Employee Name : " + EmployeeName + " \n Employee Number: " + EmployeeNumber + " \n Hire Year : " + hireyear + "\n Weekly Earnings : " + WeeklyEarning;
return data;
}
public boolean equals(Object o){
if(this == null){
return false;
}
if(this == o){
return true;
}
if(!(o instanceof Employee)){
return false;
}
Employee temp = (Employee) o;
if(this.getEmployeeName().equals(temp.getEmployeeName())){
return true;
}
if(this.getEmployeeNumber().equals(temp.getEmployeeNumber())){
return true;
}
if(this.gethireyear() == temp.gethireyear()){
return true;
}
if(this.getWeeklyEarning() == temp.getWeeklyEarning()){
return true;
}
return false;
}
}
Heres the generateList method that will populate the list:
public ArrayList<Employee> generateEmpList(){
empList = new ArrayList <Employee>();
Random empPicker = new Random();
for(int i = 0; i < 20; i++){
int id = empPicker.nextInt(20);
if(id < 12) // roll for production worker
{
//System.out.println("Adding Production Worker");
ProductionWorker temp = new ProductionWorker();
temp = temp.generateProductionWorker();
prodWorker = temp;
empList.add(prodWorker);
}
else //roll for Shift supervisor
{
//System.out.println("Adding Shift supervisor");
ShiftSupervisor supervisor = new ShiftSupervisor();
supervisor = supervisor.generateShiftSupervisor();
shiftWorker = supervisor;
empList.add(shiftWorker);
}
}
Iterator iterator = empList.iterator();
while (iterator.hasNext()) {
System.out.println("");
System.out.println(iterator.next());
}
return empList;
}
and also which could be helpful is the "generateProductionWorker()" and shiftSupervisor methods - to keep it short ill only post prod worker method cause they are basically the same:
public ProductionWorker generateProductionWorker(){
Random rng = new Random();
int numberOfEmployeeNames = Ename.length;
ProductionWorker tempPworker = new ProductionWorker();
String employeeName = Ename[rng.nextInt(numberOfEmployeeNames)];
tempPworker.setEmployeeName(employeeName);
int numberOfEmployeeNumbers = Empnum.length;
String employeeNumber = Empnum[rng.nextInt(numberOfEmployeeNumbers)];
tempPworker.setEmployeeNumber(employeeNumber);
int yearHired = rng.nextInt(35) + 1980;
tempPworker.setEmployeehireyear(yearHired);
double weeklySalary = rng.nextInt((100) * 100);
tempPworker.setEmployeeweeklyearning(weeklySalary);
int hourlyRate = rng.nextInt(20) + 10;
tempPworker.setHourlyRate(hourlyRate);
return tempPworker;
}
I'm sure I'm missing something trivial but any ideas why i get similar entries when i have a list of 20 names and numbers?
ex:
empname - josh
empnum - 0000-A
hireyear - 1994
salary - 40,000
empname - josh
empnum - 0000-A
hireyear - 1999
salary - 60,500
any advice would help, Thanks!
Look at the equals method in your Employee class. If their name are the same, you return true, which means these are equals. The same is for the other attributes. You must replace your if statements.
I agree with Georgi, you equals method is the culprit.
Currently it is returning true after the first if statement at the line that reads
if(this.getEmployeeName().equals(temp.getEmployeeName())){
return true;
}
Because it is a return statement it stops the method from continuing to the other statements. You might try this:
public boolean equals(Object o){
if(this == null){
return false;
}
if(this == o){
return true;
}
if(!(o instanceof Employee)){
return false;
}
//set all the elements in the array to false and change to true when true.
boolean [] doesItMatch = new boolean[4];
doesItMatch[0] = false;
doesItMatch[1] = false;
doesItMatch[2] = false;
doesItMatch[3] = false;
Employee temp = (Employee) o;
if(this.getEmployeeName().equals(temp.getEmployeeName())){
doesItMatch[0] = true;
}
if(this.getEmployeeNumber().equals(temp.getEmployeeNumber())){
doesItMatch[1] = true;
}
if(this.gethireyear() == temp.gethireyear()){
doesItMatch[2] = true;
}
if(this.getWeeklyEarning() == temp.getWeeklyEarning()){
doesItMatch[3] = true;
}
int check = 0;
//Now that you have checked all the values, check the array. Using a simple counter.
for(int i = 0; i < doesItMatch.length; i++){
if(doesItMatch[i]){
check++;
} else {
check--;
}
}
//The counter should be 4 when the if statements above are all true. Anything else is false.
if(check == 4){
return true;
} else {
return false;
}
}
This method now checks each of the attributes in the Employee class. (Name, Number, Hire year and so on. If you create more attributes to the class it is easy to add more elements to the array just be sure to set them to false.)
Hope this helps
This also would take a little maintenance if you expanded the Employee class so you might want to find a way to make it a little easier on yourself.

Java help! implementing a 2d array of a certain object, the object has multiple private data types and objects

I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.

How do I check if a class' return of a method equals null?

In my program, I have a while loop that will display a list of shops and asks for an input, which corresponds with the shop ID. If the user enters an integer outside the array of shops, created with a Shop class, it will exit the loop and continue. Inside this loop is another while loop which calls the sellItem method of my Shop class below:
public Item sellItem()
{
displayItems();
int indexID = Shop.getInput();
if (indexID <= -1 || indexID >= wares.length)
{
System.out.println("Null"); // Testing purposes
return null;
}
else
{
return wares[indexID];
}
}
private void displayItems()
{
System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
System.out.println("0. Return to Shops");
for(int i = 0; i < wares.length; i++)
{
System.out.print(i + 1 + ". ");
System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
}
}
private static int getInput()
{
Scanner scanInput = new Scanner(System.in);
int itemID = scanInput.nextInt();
int indexID = itemID - 1;
return indexID;
}
The while loop in my main class method is as follows:
boolean exitAllShops = true;
while(exitAllShops)
{
System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
}
else
{
System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
int confirm = scan.nextInt();
if(confirm == 1)
{
exitAllShops = false;
}
}
The problem is here:
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
No matter what I do, I can't get "still null" to print to confirm that I'm correctly calling the return statement of the method sellItem of the class Shop. What am I doing wrong?
After calling allShops[...].sellItem(), allShops is still a valid array reference -- there's no way it could be null! You probably want to test the return value from sellItem:
if(allShops[shopInput-1].sellItem() == null)

Categories