简体   繁体   English

For Each Loops和For循环Java

[英]For Each Loops and For Loops Java

I want to be able to create a for loop like this 我希望能够像这样创建一个for循环

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 我假设id需要每个循环,这将是这样的

  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. 该程序创建一个新的预订,然后允许用户将详细信息输入到该预订的程序中,我将其命名为B1。 IS it that value you enter into the for loop? 是你输入for循环的价值吗?

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. 您将需要一个预订类,以及存储在AllBookings阵列列表中的一些数据。 With you ensure that only Booking Objects can be placed within that Array List. 确保只有预订对象可以放在该阵列列表中。

But back to the For each loop. 但回到For each循环。

  1. The first part (Booking) defines which Object-type is placed in the list,array or what you want to compute through. 第一部分(Booking)定义了哪个Object-type放在列表,数组或您想要计算的内容中。 Note: You could also place Object instead of Booking since everything is an Object, but I would not recommend you to do that. 注意:您也可以放置Object而不是Booking因为一切都是Object,但我不建议您这样做。

  2. The second one (b) is the name of the variable which stands for the actual element in your list, when iterating over it. 第二个(b)是变量的名称,它代表列表中的实际元素,当迭代它时。

  3. And the third and final part (AllBookings) is your Collection or Array where all your Objects are placed in. 第三个也是最后一个部分(AllBookings)是你的所有物品所在的集合或数组。

Java Documentation for For-Each Loops: For-Each循环的Java文档:

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. Type是对象Type的名称:用于声明它的对象。 EG Booking. EG预订。

var is the name of the placeholder variable, which will assume the value of each element that you loop over in the collection. var是占位符变量的名称,它将假定您在集合中循环的每个元素的值。 This can be whatever you want. 这可以是你想要的任何东西。

coll is the name of the collection you want to loop over. coll是要循环的集合的名称。 It sounds like maybe you called this B1. 听起来好像你叫这个B1。

So you would use 所以你会用

for (Booking booking : B1){
//body
}

What is booking? 什么是预订? foreach loops are used for Array Iteration foreach循环用于Array迭代

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 []类型的数组(我可以编辑我的答案,如果它是其他的东西)

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: 如果你有一个类型为Foo的集合,如下所示:

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. 我不完全理解你在提到B1的段落中提到的内容,因为你所描述的内容似乎根本不需要循环。

But in general, the for-each loop works the way you've described. 但总的来说,for-each循环按照你所描述的方式工作。 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 ). 请注意,右侧变量称为coll - 这是因为它需要是某种元素集合(严格来说是实现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> ,您可以依次循环遍历此列表中的所有预订:

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. 该程序创建一个新的预订,然后允许用户将详细信息输入到该预订的程序中,我将其命名为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? 你想要循环的是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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