For Each Loops and For Loops Java - java

I want to be able to create a for loop like this
For(each booking)
sounds simple for all you experts out there, but ive tried researching how to do this,
and its left me a little confused,
I assume id need a for each loop, which would be something like this
for (type var : coll) {
body-of-loop
}
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1. IS it that value you enter into the for loop?
I know ill get rated down on this, but i dont understand how i get it to loop for each booking.
Thanks for the quick answers, Ive written some code which ill provide now. Hopefully it will make it easier to see.
Booking Class
public class Booking
{
private int bookingId;
private String route;
private double startTime;
private String bookingDate;
public Booking()
{
bookingId = 0000;
route = "No Route Entered";
startTime = 0.00;
bookingDate = "No Date entered";
}
public int getBookingId()
{
return bookingId;
}
public String getRoute()
{
return route;
}
public double getStartTime()
{
return startTime;
}
public String getBookingDate()
{
return bookingDate;
}
public void setBookingId(int bookingId)
{
this.bookingId = bookingId;
}
public void setRoute(String route)
{
this.route = route;
}
public void setStartTime(double startTime)
{
this.startTime = startTime;
}
public void setBookingDate(String bookingDate)
{
this.bookingDate = bookingDate;
}
public Booking(int bookingId, String route, double startTime, String bookingDate)
{
setBookingId(bookingId);
setRoute(route);
setStartTime(startTime);
setBookingDate(bookingDate);
}
public String toString()
{
return "BookingId: " + getBookingId() + "\nRoute: " + getRoute() + "\nStart Time: " + getStartTime() +
"\nBooking Date: " + getBookingDate();
}
}
Main Class
import java.util.*;
public class Main {
public static void main(String[] args) {
//<editor-fold defaultstate="collapsed" desc="Creates new Student and booking">
Student s1 = new Student();
Booking b1 = new Booking();
s1.setStudentId(Integer.parseInt(JOptionPane.showInputDialog("Enter ID for Student: [0001]")));
s1.setFname(JOptionPane.showInputDialog("Enter first name of Student: "));
s1.setLname(JOptionPane.showInputDialog("Enter last name of Student: "));
s1.setAddress(JOptionPane.showInputDialog("Enter address for Student: "));
s1.setPhoneNo(JOptionPane.showInputDialog("Enter phone number for Student: "));
s1.setOtherDetails(JOptionPane.showInputDialog("Enter other details for Student: [Glasses?]"));
b1.setBookingId(0002);
b1.setStartTime(Double.parseDouble(JOptionPane.showInputDialog("Enter Start time for Booking: [1200]")));
b1.setBookingDate(JOptionPane.showInputDialog("Enter Date for Booking: [01-JAN-12]"));
//</editor-fold>
//For Each Booking
}
}
}

List <Booking> allBookings = new ArrayList<Booking>();
//fill your AllBookings with data
for(Booking b:allBookings){
body of loop // b is your actual Booking Object
}
Something like this would do your work.
You will need an Booking Class, and some data stored in your AllBookings Array List. With you ensure that only Booking Objects can be placed within that Array List.
But back to the For each loop.
The first part (Booking) defines which Object-type is placed in
the list,array or what you want to compute through. Note: You could also place Object instead of Booking since everything is an Object, but I would not recommend you to do that.
The second one (b) is the name of the variable which stands for
the actual element in your list, when iterating over it.
And the third and final part (AllBookings) is your Collection or Array where all your Objects are placed in.
Java Documentation for For-Each Loops:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

You got the syntax right, you just need to pass a collection (or an array) of the objects to the loop:
// bookings is Booking[] or a collection of Booking objects, like List<Booking>
for (Booking b : bookings)
{
// do whatever you need to do with b
}

Type is the name of the type of your object: the thing you'd use to declare it. E.G. Booking.
var is the name of the placeholder variable, which will assume the value of each element that you loop over in the collection. This can be whatever you want.
coll is the name of the collection you want to loop over. It sounds like maybe you called this B1.
So you would use
for (Booking booking : B1){
//body
}

What is booking? foreach loops are used for Array Iteration
I'm assuming this is what you're trying to do, lets say booking is an array of type String[] (i can edit my answer if it's something else)
String[] booking = new String[]{"Hello", "How are You", "Goodbye"};
for (String s: booking)
{
System.out.println(s);
}
for (int i=0; i < booking.length; i++)
{
System.out.println(booking[i]);
}
Produces the following output:
Hello
How are You
Goodbye
Hello
How are You
Goodbye

If you have a collection of type Foo like this:
List<Foo> someList = getSomeList();
Then to loop you can do:
for(Foo myFoo : someList){
System.out.println("I have a foo : "+myFoo);
}

I don't fully understand what you're asking in the paragraph where you mention B1, as what you're describing doesn't seem to require looping at all.
But in general, the for-each loop works the way you've described. Note that the right hand variable is called coll - this is because it needs to be some sort of collection of elements (strictly something that implements Iterable). So if you have e.g. a List<Booking>, you could loop over all of the bookings in this list in turn as follows:
List<Booking> bookings = ...; // populated somehow, or passed in, whatever
for (Booking b : bookings) {
// Do what you want to b, it will be done in turn to each booking in the list
// For example, let's set the hypothetical last updated date to now
b.setLastUpdated(new Date());
}
// At this point all bookings in the list have had their lastUpdated set to now
Going back to what you described:
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1.
It sounds like you have a booking. Are you sure you need a loop for just one booking? A loop involves performing the same actions on a bunch of different objects; what is it you want to loop over?

Related

How can I show segmented information in an array?

I have to create a program which has a list of houses. In this houses there has to be this information:
direction, zipcode, number of rooms and the square meters of the house.
One of my biggest problems is that this information has to be segmented. So, first the list of directions have to be shown, then the list of zipcodes, then the number of rooms...
I created a class House and I set the String variables for each one (direction, zipcode, number of rooms and the square meters of the house).
I know that I should be using arrays, for and objects but It's my first assignment and I am really lost on how or where should I start.
I really want to learn how to do it, so if you have any idea, tip or suggestion I would appreciate it. I don't want people to do my assignment I just want to know how can I get started.
thank you!
This is my code so far:
package ejerciciofinalt3;
public class HouseExercise {
public static void main(String[] args) {
// TODO Auto-generated method stub
House house1 = new House();
house1.showHouseInfo();
house1.direction = "abc";
house1.postCode = "08397";
house1.roomNumber = "4";
house1.squareMeter = "100";
house1.showHouseInfo();
}
}
Create an ArrayList and add each house in that List. Then for each of the segments (directions, zipCodes, etc) do a for loop and print the segment:
List <House> houseL = new ArrayList();
houseL.add(house1);
houseL.add(house2);
houseL.add(house3);
System.out.println("-- Directions --");
for (House house:houseL){
System.out.println(house.getDirection());
}
System.out.println("-- Zip Codes--");
for (House house:houseL){
System.out.println(house.getPostCode());
}
//etc
You should have getters in House class.
Initialize a String Array like this:
String[] housePropertiesArray = new String[]{"abc", "08397", "4", "100"};
...in the House class.
Then you could write a method to return all of them:
public String getProperties(){
String output = "";
for(String property : housePropertiesArray){
output += property + "\n";
}
return output;
}
In the outputString you would have a superfluous \n in the end, just a newLine-Tag but wouldnt matter much I hope.
Try to override the toString() method like
class House{
...
#override
public String toString(){
return String.format("direction: %s postCode: %s roomNumber: %s squareMeter : %s",
this.direction, this.postCode, this.roomNumber, this.squareMeter);
}
after if you want to display just call
System.out.println(house.toString());
Or
System.out.println(house);

How to erase a current object using a function | Java

I am trying to make an erase function to delete the teams of the tournament using the team code (value c in the constructor). Firstly I want to check if that team exists in the objects I made in the main method. Is that possible to do that using an if statement?
Exercise:
Create a java application that stores data for various football teams. Each team has a name, a code and the current points in the championship. In your class create methods for registering new teams, erasing existing teams using their code and showing a list for all the teams currently active in the championship
package assignment.exercise4;
public class Data {
private String name = "";
private int code = 0;
private static int register;
private int erase;
private int currentpoints = 0;
public Data(int c, int points, String n) { //constructor
code = c;
this.currentpoints = points;
name = n;
}
public void Erase(int c)
{
code = c;
if(code != 0)
System.out.println("Team with Code: "+code+" has been erased" );
else
System.out.print("Team with code "+code+" does not exist!");
}
public void Register(String newTeam,int code)
{
name = newTeam;
this.code = code;
System.out.println("New Team " + name + " registered with code " + code);
}
public void print()
{
System.out.println("Team name: " + name + "\nTeam code: " + code + "\nTeam points: " + currentpoints + "\n");
}
}
/*
public static void main(String[] args) {
System.out.println("\nList of Teams: \n");
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
Data Team = new Data(0,0,""); //use for erase
t1.print();
t2.print();
t3.print();
t4.print();
System.out.println("Teams erased: \n");
Team.Erase(110);
Team.Erase(122);
Team.Erase(0);
System.out.println("\n\nTeams Registered: \n");
t1.Register("Real madrid", 11);
t1.Register("Atletico Madric", 112);
}
}
*/
What are you trying to erase the teams from?
If they were in a list, for example...
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
List<Data> teams = Arrays.asList(t1, t2, t3, t4);
...you could create a list with a team erased like this...
public List<Data> erase(List<Data> team, int id) {
return team.stream()
.filter(t -> t.getId() != id)
.collect(Collectors.toList());
}
So...
List<Data> remainingTeam = erase(team, 122); // Removes Arsenal
...would remove the first element from the list
I will not answer this to elaborately since it is homework. I will try to give you a hint though.
If you have a team and want to do something with it. Otherwise you just have a team which just stays there in a particular scope (if you do not know what scope is, look it up!). If you have a team you most likely want do do something with it. In this case you seem to want to store information about the teams to use in a championship. Important to note here is that the teams are not the focus here. The real focus is the Championship. The teams are just a part of the championship. There can still be a championship even if all teams does not choose to participate. But you want all teams choosing to participate to be registered to this particular championship (eg UEFA Champions League).
This leads to something called aggregate or association depending on how hard you want to tie the object to the championship. However you do probably not need to pursue these terms any further at this point. What is important to remember is that there is an "has a" relation between the championship and the teams. The championship "has a" collection of participating teams. This is normally reflected in this way in code,
public class Championship {
private Team[] teams; // Or List<Team>, Collection<Team>, HashMap<Team>, ...
}
The Championship can then have methods for registering a team, removing a team, updating status, etc...
public void register(Team t) {
if (numberOfTeams < teams.length) {
teams[numberOfTeams] = t; // Index starts at zero
numberOfTeams++;
} else {
throw new IndexOutOfBoundsException("The list is full. " +
"No more teams may be registered!")
}
}
Even though the function erasing a team was requested, I believe I will not write it down. This design is so different from your original intent, so that writing the erase function will likely solve your complete homework. However, you do actually not have to erase the team it is perfectly possible to just overwrite the position with the next team as,
teams[i] = teams[i+1];
Hope this helps!
Short answer:
public void erase(int id) {
// who needs an if statement, if we can use predicates?
teams.removeIf(team -> team.getId() == id);
}
But this will not work with your current code. Your current code misses the container for your teams.
Longer answer:
For the fun of it. Solving your homework:
class Team {
int id;
String name;
int points;
Team(int id, String name, int points) {
this.id = id;
this.name = name;
this.points = points;
}
#Override
public String toString() {
// ugly formatted... another homework? ;-)
return "Team '" + name + "' (" + id + "): " + points;
}
}
Note, that I will not add any getter or setter, nor will I care about visibility here. I will leave that as another homework for you.
class Championship {
List<Team> teams = new ArrayList<>();
void register(Team team) {
teams.add(team);
}
void erase(int id) {
teams.removeIf(team -> team.id == id);
}
#Override
public String toString() {
// for additional fun... sorted by descending points
return "=== Championship table ===\n"
+ teams.stream()
.sorted((o1, o2) -> Integer.compare(o2.points, o1.points))
.map(Objects::toString)
.collect(Collectors.joining("\n"));
}
}
Somewhere else:
public static void main(String[] args) {
Championship championship = new Championship();
championship.register(new Team(1, "not the best ones", 3));
championship.register(new Team(2, "The better ones", 7));
championship.register(new Team(3, "The winners", 11));
System.out.println(championship);
championship.erase(3);
System.out.println(championship);
}
Output:
=== Championship table ===
Team 'The winners' (3): 11
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
=== Championship table ===
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
Too much of information? Just start with something like a championship-class or at least use a collection of Teams (e.g. List<Team>).
By the way... Do not deliver this solution as your homework, except you understand what is going on and you can explain it with your own words. Otherwise you are only betraying yourself.

Checking if there is a certain string in an object contained in an ArrayList, then adding the object to another ArrayList

I have Arraylist of objects ArrayList<Product> productDatabase. The object contains a String and a double and then these objects will be added to the productDatabase by addProductToDatabase(); as follows:
public void addProductToDatabase(String productName, double dimensions); {
Product newProduct = new Product(ProductName, dimensions);
productDatabase.add(newProduct);
}
I also want to make an Arraylist<ProductCount> productInventory which counts how many Product are accounted for. Before it can add to ArrayList<ProductCount> productInventory however, it should first check if the object details exist in the productDatabase while running addProductToInventory()
public Product getProduct(String name) {
for(i = 0; i < productDatabase.size(); i++)
if(productDatabase.get(i).contains(name) //Error: cannot find symbol- method contains.(java.lang.String)
return productDatabase.get(i)
}
public void addProductToInventory(String productName, double quantity)
{
Product p = getProduct(name);
productCount.add(new ProductCount(o, quantity));
}
Assume that you always have different objects (so nothing will have the same name), but you're always unsure of the dimensions (so when you input the same producttName + dimensions you edit the dimensions in it).
At the end of the day, you have to put all the items in it a large box and report what you've inventoried, so you also have a getProductQuantityTotal() and you have to getProductDimensionTotal()-- as the name suggests, get the total of number of objects you've counted, and the sum of the dimensions.
What do I have to add/change/remove about this code? Don't consider syntax first (because BlueJ checks for common syntax errors and I just typed this by hand). I'm sure that I'm missing a for statement somewhere, and I'm probably misusing contains() because it won't recognise it (I have import java.util.*; and import java.util.ArrayList;)
To answer the question in your post title: How to find a string in an object, for a list of those objects, here is some sample code that does this:
First, I created a trivial object that has a string field:
class ObjectWithStringField {
private final String s;
public ObjectWithStringField(String s) {
this.s = s;
}
public String getString() {
return s;
}
}
And then a code that populates a list of it, and then searches each for the string. There's no magic here, it just iterates through the list until a match is found.
import java.util.List;
import java.util.Arrays;
/**
<P>{#code java StringInObjectInList}</P>
**/
public class StringInObjectInList {
public static final void main(String[] ignored) {
ObjectWithStringField[] owStrArr = new ObjectWithStringField[] {
new ObjectWithStringField("abc"),
new ObjectWithStringField("def"),
new ObjectWithStringField("ghi")};
//Yes this is a List instead of an ArrayList, but you can easily
//change this to work with an ArrayList. I'll leave that to you :)
List<ObjectWithStringField> objWStrList = Arrays.asList(owStrArr);
System.out.println("abc? " + doesStringInObjExistInList("abc", objWStrList));
System.out.println("abcd? " + doesStringInObjExistInList("abcd", objWStrList));
}
private static final boolean doesStringInObjExistInList(String str_toFind, List<ObjectWithStringField> owStrList_toSearch) {
for(ObjectWithStringField owStr : owStrList_toSearch) {
if(owStr.getString().equals(str_toFind)) {
return true;
}
}
return false;
}
}
Output:
[C:\java_code\]java StringInObjectInList
abc? true
abcd? false
In the real world, instead of a List, I'd use a Map<String,ObjectWithStringField>, where the key is that field. Then it'd be as simple as themap.containsKey("abc");. But here it is implemented as you require. You'll still have quite a bit of work to do, to get this working as specifically required by your assignment, but it should get you off to a good start. Good luck!

TreeSets and removing specific unnamed Objects

So I'm writing a program for an assignment where I store Patients into a TreeSet. The problemn I'm having is I have to implement a method to discharge a specefic patient from the TreeSet.
for(int i = 0; i < 10 ; i++){
Random ag = new Random();
int age = ag.nextInt(99) + 1;
Names randomname = Names.getRandom();
String name = randomname.name();
String sex;
if(Math.random() > 0.5)sex = "female";
else sex = "male";
Random sn = new Random();
int serial = sn.nextInt(10000) + 1;
Address randomAddress = Address.getRandom();
String address = randomAddress.name();
Hospital.admitPatient(new Patient(age, name, sex, serial, Birthday.produceBirthday(), address));
}
So Thats how I am looping to get the Patients info and stats for the Patient Object. The admit patient method adds them to the TreeSet.
public static void admitPatient(Patient obj){
if(numofPatients < maxPatients){
patientList1.add(obj);
}
}
The Problem I'm having is withbthe Discharge patient method. Where I don't know what to put in the method
public static void dischargePatient(What do i put here in the driver when i call this method?){
patientList1.remove(w/e i put up there);
}
Since I didn't name the Objects of patients when creating them but just inserted them straight into the TreeSet I'm not sure exactly how to call them when i call the discharge patient method.
As you usually want to work with selected objects (patients) and not the whole list, you need a way to identify them somehow (for example by name or ID).
Since add and remove are similar, your dischargePatient method will be similar as well. Try
public static void dischargePatient(Patient patient) {
patientList1.remove(patient);
}
To retrieve a patient with a certain ID, you may iterate through your set and return it:
public Patient getPatientByID(String id) {
for (Patient patient : patientList1) {
if (patient.getID().equals(id)) {
return patient;
}
}
}
To remove a patient with ID "1234abc", you could do the following:
dischargePatient(getPatientByID("1234abc"));
Using this pattern, you rebuild the functionality of the map datastructure. Thus it might be better to use a Map (e.g. HashMap<>). Code will be reduced to operations like:
Map<String, Patient> patients = new HashMap<>();
patients.put("1234abc", patient1);
patients.remove("1234abc");
Full code for your example:
public static void admitPatient(Patient patient) {
if(numofPatients < maxPatients){
patients.put(patient.getID(), patient);
}
}
public static void dischargePatient(String id) {
patients.remove(id);
}

3-dimensions different types Map or List: List(ID=integer) of List(ID=integer) of int[]

I'm going to build a hotel table.
But I'm having problems when trying to implement this in Java.
My hotel has Level(int id) x Room(int id) x Field(String status, int counter)
The same in php would look like:
$level=1; $room=2;
if(isset($hotel[$level][$room])) {
print("Room: ".$level*100+$room);
print(", Status: ".$hotel[$level][$room]['status']);
print(", Total clients:".$hotel[$level][$room]['counter']);
}
And this print returns me(if room exist):
"Room: 102, Status: Reserved, Total clients: 8";
Now I want to have the same in JAVA.
But the problem is, that I'm not able to build this:
int[][][] my hotel;
Because, I have the different types in my multi-dimensional array.
I tried to make sth like this:
Map<String, List<String>> myHotel = new HashMap<String, List<String>>();
Or:
List<List<List<String>>> myHotel;
But
out.println(
myHotel.get(1).get(2).get("status") + "\n" +
out.println(myHotel.get(1).get(2).get("status"));
Or even:
out.println("Status:" +
myHotel.get(1).get(2).get(0) + "\tClients:" +
myHotel.get(1).get(2).get(1)
);
Also how to put elements. I'm thinking about sth like:
WHEN it's a MAP table:
myHotel.put(1).add(2).add(0, "Reserved"));
// But better would be:
// myHotel.put(1).add(2).add("status", "Reserved"));
Or WHEN it's a List<List<List<String>>>:
myHotel.add(1).add(2).add(0, "Reserved"));
// But better would be:
// myHotel.add(1).add(2).add("status", "Reserved"));
Thanks for helping :)
I'd probably model the hotel as an object Hotel, the room as an object Room etc. rather than stacking everything together in a multi-tiered collection. That becomes very verbose very quickly, and as soon as you change the relationships then that change is reflected throughout your code.
Each object then contains references to its components (Hotel contains a list of Rooms etc.). Once you do this I think everything should become a lot clearer. Furthermore your Hotel object understands how to find Rooms, the Room objects understand how to get its attributes and your calling code becomes a lot less verbose, and a lot less dependent on the Hotel/Room implementation. e.g. you can do this:
Hotel hotel = new Hotel();
Set<Room> rooms = hotel.getFreeRooms(RoomType.NON_SMOKING);
and so your objects do the work for you (the client) rather than you navigating the object hierarchy and doing the work yourself.
That's the ultimate goal of OO. As soon as I find myself putting together collections of collections, that's often an indicator that a new object class is required.
You should create proper classes
import java.util.*;
class Hotel {
public List<Level> levels = new ArrayList<Level>();
}
class Level {
public List<Room> rooms = new ArrayList<Room>();
}
class Room {
public Status status = Status.FREE;
public int counter = 0;
}
enum Status {
FREE, OCCUPIED
}
and then you use
Hotel hotel = new Hotel();
hotel.levels.add(new Level());
hotel.levels.get(0).rooms.add(new Room());
Room room = hotel.levels.get(0).rooms.get(0);
room.status = Status.OCCUPIED;
room.counter = 8;
et cetera...
NB: of course, OO purists will no come and tell you that all these fields need to be private and only be accessed through accessors. But I'd say it's okay if you start with this most simple design and later, as you learn more Java, evolve it to something more complex.
class HotelRoom{
int roomnumber;
int level;
boolean reserved;
int clientCount;
public int getUniqueNumber(){
return roomnumber + level*100;
}
}
...
HotelRoom[][] hotel = new HotelRoom[floorCount][roomCount];
HotelRoom myRoom = hotel[floor][room];
System.out.print("room: " + myRoom.getUniqueNumber());
System.out.print(", Status: " myRoom.reserved);
System.out.print(", Total clients: " myRoom.clientCount);
Your design is pretty crazy, by the way.
Since level and room number is the key, I would represent room as a value object like this (at a minimum):
class Room {
public static enum Status {RESERVED, AVAILABLE}
private Status status;
private int numberOfPersons;
// Getters and setters
}
And the key as:
class RoomKey {
private int levelNumber;
private int roomNumber;
public RoomKey(int levelNumber, int roomNumber) {
this.leveNumber = levelNumber;
this.roomNumber = roomNumber;
}
}
And keep the data in a Map like:
Map<RoomKey, Room> rooms = getRoomMap();
Room room = rooms.get(new RoomKey(levelNumber, roomNumber))

Categories

Resources