简体   繁体   English

Java中是否允许多个&&语句?

[英]Is multiple && statements allowed in Java?

Is the following code allowed in Java? Java是否允许以下​​代码? My program doesn't work unless I comment this line out and I am not sure if the multiple && statements in the if is allowed. 除非我注释掉这一行,否则我的程序将无法运行,并且不确定是否可以使用if中的多个&&语句。

if(number.isBusy() && number2.isBusy() && number3.isBusy() && number4.isBusy() && number5.isBusy() ) {}

Edited to add: If you comment out the line that is given above, the program will actually display something in the output window (although the only thing that gets something added to it is "number5") if it is left in, all of the outputs are zero. 编辑添加:如果您注释掉上面给出的行,则该程序实际上将在输出窗口中显示某些内容(尽管唯一添加了内容的内容是“ number5”),如果保留了该内容,则所有输出为零。

This is the entire program right now: 现在是整个程序:

// FILE: Line.java
// This program illustrates the use of the lineSimulate method which uses
// a simple queue to simulate cars waiting at a car wash.

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
// import edu.colorado.simulations.BooleanSource;
// import edu.colorado.simulations.Line ;
// import edu.colorado.simulations.Averager;

/******************************************************************************
* The <CODE>CarWash</CODE> Java application illustrates the use of
* the <CODE>lineSimulate</CODE> method.
* The illustration uses the following values:
*   <CODE>
*   <br>lineTime = 240
*   <br>arrivalTime = 0.0025
*   <br>totalTime = 6000
*   </CODE>
*
* <p><dt><b>Java Source Code for this class:</b><dd>
*   <A HREF="../applications/CarWash.java">
*   http://www.cs.colorado.edu/~main/applications/CarWash.java
*   </A>
*
* @author Michael Main 
*   <A HREF="mailto:main@colorado.edu"> (main@colorado.edu) </A>
*
* @version
*   Jun 12, 1998
******************************************************************************/
public class LineWait
{
   /**
   * The main method activates <CODE>lineSimulate</CODE> with the values:
   *   <CODE>
   *   <br>lineTime = 240
   *   <br>arrivalTime = 0.0025
   *   <br>totalTime = 6000
   *   </CODE>
   * <BR>The <CODE>String</CODE> argument (<CODE>args</CODE>) is not used in
   * this implementation.
   **/
   public static void main(String[ ] args)
   {

      final int LINETIME = 100 + (int)(Math.random() * ((400) + 1));
      final double ARRIVALPROB = (Math.random() * ((.1) + 1));
      final int TOTALTIME = 6000;

      lineSimulate(LINETIME, ARRIVALPROB, TOTALTIME);
   }

   /**
   * Simulate the running of a car washer for a specified amount of time.
   * @param <CODE>lineTime</CODE>
   *   the number of seconds required to wash one car
   * @param <CODE>arrivalProb</CODE>
   *   the probability of a customer arriving in any second, for example
   *   0.1 is 10%
   * @param <CODE>totalTime</CODE>
   *   the total number of seconds for the simulation
   * <dt><b>Precondition:</b><dd>
   *   <CODE>lineTime</CODE> and <CODE>totalTime</CODE> are positive;
   *   <CODE>arrivalProb</CODE> lies in the range 0 to 1.
   * <dt><b>Postcondition:</b><dd>
   *   The method has simulated a car wash where <CODE>lineTime</CODE> is the
   *   number of seconds needed to wash one car, <CODE>arrivalProb</CODE> is
   *   the probability of a customer arriving in any second, and
   *   <CODE>totalTime</CODE> is the total number of seconds for the
   *   simulation. Before the simulation, the method has written its three
   *   parameters to <CODE>System.out</CODE>. After the simulation, the method
   *   has written two pieces of information to <CODE>System.out</CODE>:
   *   (1) The number of cars washed, and (2) The average waiting time for
   *   customers that had their cars washed. (Customers that are still in the 
   *   queue are not included in this average).
   * @exception java.lang.IllegalArgumentException
   *   Indicates that one of the arguments violates the precondition.
   **/
   public static void lineSimulate
   (int lineTime, double arrivalProb, int totalTime)
   {  
      Queue<Integer> arrivalTimes = new LinkedList<Integer>( ); 
      Queue<Integer> arrivalTimes2 = new LinkedList<Integer>( );  
      Queue<Integer> arrivalTimes3 = new LinkedList<Integer>( );
      Queue<Integer> arrivalTimes4 = new LinkedList<Integer>( );
      Queue<Integer> arrivalTimes5 = new LinkedList<Integer>( );
      int next;
      BooleanSource arrival = new BooleanSource(arrivalProb);
      Line number = new Line(lineTime);
      Line number2 = new Line(lineTime);
      Line number3 = new Line(lineTime);
      Line number4 = new Line(lineTime);
      Line number5 = new Line(lineTime);
      Averager waitTimes = new Averager( );
      Averager waitTimes2 = new Averager();
      Averager waitTimes3 = new Averager();
      Averager waitTimes4 = new Averager();
      Averager waitTimes5 = new Averager();
      int currentSecond;
      // Write the parameters to System.out.
      System.out.println("Seconds to wait in line " + lineTime);
      System.out.print("Probability of customer arrival during a second: ");
      System.out.println(arrivalProb);
      System.out.println("Total simulation seconds: " + totalTime); 

      // Check the precondition:
      if (lineTime <= 0 || arrivalProb < 0 || arrivalProb > 1 || totalTime < 0)
         throw new IllegalArgumentException("Values out of range");        




      for (currentSecond = 0; currentSecond < totalTime; currentSecond++)
      {  // Simulate the passage of one second of time.

         // Check whether a new customer has arrived.
         if (arrival.query( ))
            {
                System.out.println("Test1");
                if(number.isBusy() && number2.isBusy() && number3.isBusy() && number4.isBusy() && number5.isBusy() )
                {
                   System.out.println("Test2");
                    if(arrivalTimes.size() < arrivalTimes2.size() && arrivalTimes.size() < arrivalTimes3.size() && arrivalTimes.size() < arrivalTimes4.size() && arrivalTimes.size() < arrivalTimes5.size()) 
                    {
                        arrivalTimes.add(currentSecond);
                        System.out.println("Test");
                    }
                    else if(arrivalTimes2.size() < arrivalTimes.size() && arrivalTimes2.size() < arrivalTimes3.size() && arrivalTimes2.size() < arrivalTimes4.size() && arrivalTimes2.size() < arrivalTimes5.size())
                    {
                        arrivalTimes2.add(currentSecond);
                        System.out.println("Test");
                    }
                    else if(arrivalTimes3.size() < arrivalTimes.size() && arrivalTimes3.size() < arrivalTimes2.size() && arrivalTimes3.size() < arrivalTimes4.size() && arrivalTimes3.size() < arrivalTimes5.size())
                    {
                        arrivalTimes3.add(currentSecond);
                        System.out.println("Test");
                    }
                    else if(arrivalTimes4.size() < arrivalTimes.size() && arrivalTimes4.size() < arrivalTimes3.size() && arrivalTimes4.size() < arrivalTimes2.size() && arrivalTimes4.size() < arrivalTimes5.size())
                    {
                        arrivalTimes4.add(currentSecond);
                        System.out.println("Test");
                    }
                    else{arrivalTimes5.add(currentSecond);}
                }

            }

             // Check whether we can put the person into a line.
             if ((!number.isBusy( ))  &&  (!arrivalTimes.isEmpty( )))
             {
                next = arrivalTimes.remove( );
                waitTimes.addNumber(currentSecond - next);
                number.startMoving( );
             }
             if ((!number2.isBusy( ))  &&  (!arrivalTimes2.isEmpty( )))
             {
                next = arrivalTimes2.remove( );
                waitTimes2.addNumber(currentSecond - next);
                number2.startMoving( );
             }
             if ((!number3.isBusy( ))  &&  (!arrivalTimes3.isEmpty( )))
             {
                next = arrivalTimes3.remove( );
                waitTimes3.addNumber(currentSecond - next);
                number3.startMoving( );
             }
             if ((!number4.isBusy( ))  &&  (!arrivalTimes4.isEmpty( )))
             {
                next = arrivalTimes4.remove( );
                waitTimes4.addNumber(currentSecond - next);
                number4.startMoving( );
             }
             if ((!number5.isBusy( ))  &&  (!arrivalTimes5.isEmpty( )))
             {
                next = arrivalTimes5.remove( );
                waitTimes5.addNumber(currentSecond - next);
                number5.startMoving( );
             }


         // Subtract one second from the remaining time in the current li
         number.reduceRemainingTime( );
         number2.reduceRemainingTime( );
         number3.reduceRemainingTime( );
         number4.reduceRemainingTime( );
         number5.reduceRemainingTime( );
        }   




      // Write the summary information about the simulation.
      System.out.println("\nCustomers served Line1: " + waitTimes.howManyNumbers( )); 
      if (waitTimes.howManyNumbers( ) > 0)
         System.out.println("Average wait Line1: " + waitTimes.average( ) + " sec");
         System.out.println("\nCustomers served Line2: " + waitTimes2.howManyNumbers( )); 
      if (waitTimes.howManyNumbers( ) > 0)
         System.out.println("Average wait Line2: " + waitTimes2.average( ) + " sec");
       System.out.println("\nCustomers served Line3: " + waitTimes3.howManyNumbers( )); 
      if (waitTimes.howManyNumbers( ) > 0)
         System.out.println("Average wait Line3: " + waitTimes3.average( ) + " sec");
       System.out.println("\nCustomers served Line4: " + waitTimes4.howManyNumbers( )); 
      if (waitTimes.howManyNumbers( ) > 0)
         System.out.println("Average wait Line4: " + waitTimes4.average( ) + " sec");
          System.out.println("\nCustomers served Line5: " + waitTimes5.howManyNumbers( )); 
      if (waitTimes.howManyNumbers( ) > 0)
         System.out.println("Average wait Line5: " + waitTimes5.average( ) + " sec");

} 
}

The expression is perfectly legal syntax. 该表达式完全合法。 The && operator is a short-circuit logical AND: the evaluation proceeds left to right and will stop at the first term (if any) that evaluates to false . &&运算符是短路逻辑AND:评估从左到右进行,将在评估为false的第一项(如果有)处停止。

EDIT 编辑

Based on your edit, I'm guessing that the problem is that the body of the if is entered only if all of number , . 根据您的编辑,我猜测,问题是,身体if只有所有的输入number . ., number5 are busy. 。, number5很忙。 (This is just a guess because you don't post what the Line class looks like or exactly what what behavior you want to see.) (这只是一个猜测,因为您没有发布Line类的外观或您想要看到的行为的确切信息。)

As a side note, I think your program would be a lot more readable (and maintainable) if you defined a class that encapsulated a Queue , a Line and an Averager . 附带说明一下,我认为如果您定义一个封装了QueueLineAverager的类,则程序将更具可读性(可维护性)。 (Presumably these three objects taken together make up something meaningful to your problem domain.) Then you could declare an array (or, perhaps better, a List ) of these objects and work with them instead of working with them as independent variables. (大概这三个对象一起构成了对您的问题域有意义的东西。)然后,您可以声明这些对象的数组(或者更好的是List )并使用它们,而不是将它们作为独立变量使用。

是的,一个人可以将有效数量的逻辑运算符链接在一起。

Yes, this is allowed. 是的,这是允许的。 The && is the shortcircuit operator, so once one of the predicates fails no further evaluation will occur. &&是短路运算符,因此一旦其中一个谓词失败,就不会进行进一步的评估。 If you want all the conditions to be evaluated you can use & (ie only one ampersand) and all predicates will evaluated. 如果要评估所有条件,则可以使用&(即,一个&符号),并且所有谓词都将被评估。 The primary reason for wanting this is if the predicates have side-effects that you want to occur. 希望这样做的主要原因是谓词是否具有要发生的副作用。 That's usually bad practice but in your case it looks like that's what you want... 这通常是不好的做法,但就您而言,这就是您想要的...

if (number.isBusy() &
    number2.isBusy() &
    number3.isBusy() &
    number4.isBusy() & 
    number5.isBusy()) {
}

each of the isBusy() will execute and the result will be the AND of the return values. 每个isBusy()将执行,结果将是返回值的与。

if (number.isBusy() &&
    number2.isBusy() &&
    number3.isBusy() &&
    number4.isBusy() &&
    number5.isBusy()) {
}

each isBusy() will execute until one fails, the following isBusy() 's won't be called. 每个isBusy()都会执行直到失败为止,以下isBusy()不会被调用。

user1247751 should provide more information for a better answer. user1247751应该提供更多信息以获得更好的答案。

However, with the information provided, I can speculate that one of the isBusy methods changes the state of the system so that it does not work. 但是,根据提供的信息,我可以推测isBusy方法之一更改了系统的状态,因此它不起作用。

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

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