简体   繁体   中英

For Each Loops and For Loops 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.

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

  2. The second one (b) is the name of the variable which stands for the actual element in your list, when iterating over it.

  3. 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:

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. EG 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 eg 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM