编写复杂的Java布尔表达式

时间:2015-07-08 19:44:10

标签: java

我正在尝试编写一个代码,如果满足以下条件,它会说嫁给我,否则就会说迷路了。

需要满足的条件:

22至27岁男性,禁烟,身高72英寸,体重不足160磅,外表漂亮,能够重新安置。“

这是我到目前为止编写的代码。 然而,即使我认为它符合给定的标准,它的打印也会丢失?怎么了?

此外,我怎么能用一个布尔值来表示呢?

public class marry {

    public static void main(String[] args) {
        int weight = 150;
        int age = 24;
        int height = 71;
        boolean isASmoker = false;
        boolean isMale = true;
        boolean isGoodLooking = true;
        boolean isAbleToRelocate = true;

        if (((weight < 160 && (age <= 27 && age >= 22)) && ((height < 72) && ((isASmoker = false) && (isMale = true))) && ((isGoodLooking = true) && (isAbleToRelocate = true)))) {
            System.out.println("Marry Me!");
        }
        else {
            System.out.println("Get Lost!");
        }
    }
}

由于

4 个答案:

答案 0 :(得分:3)

您的布尔表达式不正确。单身&#34; =&#34;执行任务。你需要&#34; ==&#34;用于布尔比较。

更改

isASmoker = false

isASmoker == false

并且

isMale = true

isMale == true

至于可读性,通过删除不必要的括号并将(variable == false)更改为!变量,可以清除整个表达式。这在某种程度上是一个偏好问题,尽管我认为大多数人会同意,正如所写,这个表达很长很难以理解。

答案 1 :(得分:1)

尝试使用我的一小段代码来确定您的问题:

class Person {
    private int weight;
    private int age;
    private int height;
    private boolean isASmoker;
    private boolean isMale;
    private boolean isGoodLooking;
    private boolean isAbleToRelocate;

    public Person(int weight, int age, int height, boolean isASmoker, boolean isMale, boolean isGoodLooking, boolean isAbleToRelocate) {
        this.weight = weight;
        this.age = age;
        this.height = height;
        this.isASmoker = isASmoker;
        this.isMale = isMale;
        this.isGoodLooking = isGoodLooking;
        this.isAbleToRelocate = isAbleToRelocate;
    }

    public boolean isGood() {
        return weight < 160 && age <= 27 && age >= 22 && 
               height < 72 && !isASmoker && isMale && 
               isGoodLooking && isAbleToRelocate;
               // (variable == true) => variable
               // (variable == false) => !variable
    }

    public static void main(String[] args) {
        Person person = new Person(150, 24, 71, false, true, true, true);
        System.out.println(person.isGood() ? "Marry Me!" : "Get Lost!");
    }
}

答案 2 :(得分:1)

==

尝试这样做,它可能会起作用

如果要检查布尔值是否为真,则甚至不必使用isMale运算符。您可以在if语句中使用布尔值(例如=)。你最初出错的地方是使用if语句中的==运算符而不是df.to_sql('test_table', engine, if_exists='append', index=False, chunksize=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/7ff6xgw24wvny74gfgzcvf6p88vc6k1a-pandas-0.15.2-16/lib/pandas/core/generic.py", line 966, in to_sql dtype=dtype) File "/7ff6xgw24wvny74gfgzcvf6p88vc6k1a-pandas-0.15.2-16/lib/pandas/io/sql.py", line 538, in to_sql chunksize=chunksize, dtype=dtype) File "/7ff6xgw24wvny74gfgzcvf6p88vc6k1a-pandas-0.15.2-16/lib/pandas/io/sql.py", line 1172, in to_sql table.insert(chunksize) File "/7ff6xgw24wvny74gfgzcvf6p88vc6k1a-pandas-0.15.2-16/lib/pandas/io/sql.py", line 717, in insert self._execute_insert(conn, keys, chunk_iter) File "/7ff6xgw24wvny74gfgzcvf6p88vc6k1a-pandas-0.15.2-16/lib/pandas/io/sql.py", line 692, in _execute_insert conn.execute(self.insert_statement(), data) File "/6rr1fqx3n9i93camwqhpfvylis5knyxh-python-sqlalchemy-0.7.9/lib/python2.7/site-packages/SQLAlchemy-0.7.9-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1449, in execute params) File "/6rr1fqx3n9i93camwqhpfvylis5knyxh-python-sqlalchemy-0.7.9/lib/python2.7/site-packages/SQLAlchemy-0.7.9-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1584, in _execute_clauseelement compiled_sql, distilled_params File "/6rr1fqx3n9i93camwqhpfvylis5knyxh-python-sqlalchemy-0.7.9/lib/python2.7/site-packages/SQLAlchemy-0.7.9-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1698, in _execute_context context) File "/6rr1fqx3n9i93camwqhpfvylis5knyxh-python-sqlalchemy-0.7.9/lib/python2.7/site-packages/SQLAlchemy-0.7.9-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1691, in _execute_context context) File "/6rr1fqx3n9i93camwqhpfvylis5knyxh-python-sqlalchemy-0.7.9/lib/python2.7/site-packages/SQLAlchemy-0.7.9-py2.7-linux-x86_64.egg/sqlalchemy/engine/default.py", line 331, in do_execute cursor.execute(statement, parameters) File "/six2r9cj6gx8yhdpjygflakgnxyjxj2y-sybase-15.0-jump1.00-3/lib-python/Sybase.py", line 546, in execute self._start() File "/six2r9cj6gx8yhdpjygflakgnxyjxj2y-sybase-15.0-jump1.00-3/lib-python/Sybase.py", line 695, in _start return self._mainloop() File "/six2r9cj6gx8yhdpjygflakgnxyjxj2y-sybase-15.0-jump1.00-3/lib-python/Sybase.py", line 709, in _mainloop self._raise_error(e) File "/six2r9cj6gx8yhdpjygflakgnxyjxj2y-sybase-15.0-jump1.00-3/lib-python/Sybase.py", line 753, in _raise_error raise exc sqlalchemy.exc.DatabaseError: (DatabaseError) Msg 102, Level 15, State 181, Line 1 Incorrect syntax near ','. 'INSERT INTO test_table ("Token", "AssetToken", "InstrumentName", "Symbol", "Series", "Reserved1", "ExpiryDate", "StrikePrice", "OptionType", "Category", "CALevel", "ReservedIdentifier", "PermittedToTrade", "IssueRate", "SecurityStatusA", "EligibilityA", "ReservedA", "SecurityStatusB", "EligibilityB", "ReservedB", "SecurityStatusC", "EligibilityC", "ReservedC", "SecurityStatusD", "EligibilityD", "ReservedD", "IssueStartDate", "InterestPaymentDate", "IssueMaturityDate", "MarginPercentage", "MinimumLotQuantity", "BoardLotQuantity", "TickSize", "IssuedCapital", "FreezeQuantity", "WarningQuantity", "ListingDate", "ExpulsionDate", "ReadmissionDate", "RecordDate", "NoDeliveryStartDate", "NoDeliveryEndDate", "LowPriceRange", "HighPriceRange", "ExDate", "BookClosureStartDate", "BookClosureEndDate", "LocalLDBUpdateDateTime", "ExerciseStartDate", "ExerciseEndDate", "TickerSelection", "OldTokenNumber", "CreditRating", "Name", "EGMAGM", "InterestDivident", "RightsBonus", "MFAON", "Remarks", "ExStyle", "ExAllowed", "ExRejectionAllowed", "PlAllowed", "CheckSum", "IsCOrporateAdjusted", "SymbolForAsset", "InstrumentOfAsset", "BasePrice", "DeleteFlag") VALUES (@Token, @AssetToken, @InstrumentName, @Symbol, @Series, @Reserved1, @ExpiryDate, @StrikePrice, @OptionType, @Category, @CALevel, @ReservedIdentifier, @PermittedToTrade, @IssueRate, @SecurityStatusA, @EligibilityA, @ReservedA, @SecurityStatusB, @EligibilityB, @ReservedB, @SecurityStatusC, @EligibilityC, @ReservedC, @SecurityStatusD, @EligibilityD, @ReservedD, @IssueStartDate, @InterestPaymentDate, @IssueMaturityDate, @MarginPercentage, @MinimumLotQuantity, @BoardLotQuantity, @TickSize, @IssuedCapital, @FreezeQuantity, @WarningQuantity, @ListingDate, @ExpulsionDate, @ReadmissionDate, @RecordDate, @NoDeliveryStartDate, @NoDeliveryEndDate, @LowPriceRange, @HighPriceRange, @ExDate, @BookClosureStartDate, @BookClosureEndDate, @LocalLDBUpdateDateTime, @ExerciseStartDate, @ExerciseEndDate, @TickerSelection, @OldTokenNumber, @CreditRating, @Name, @EGMAGM, @InterestDivident, @RightsBonus, @MFAON, @Remarks, @ExStyle, @ExAllowed, @ExRejectionAllowed, @PlAllowed, @CheckSum, @IsCOrporateAdjusted, @SymbolForAsset, @InstrumentOfAsset, @BasePrice, @DeleteFlag)' {'@InterestPaymentDate': 0, '@WarningQuantity': 0.0, '@IssueRate': 0, '@ExStyle': 'E', '@IsCOrporateAdjusted': 'N', '@BookClosureStartDate': 0, '@BasePrice': 242030, '@ExerciseStartDate': 1127520000, '@OptionType': 'CE', '@BookClosureEndDate': 0, '@EGMAGM': 0, '@OldTokenNumber': 1, '@ExAllowed': 'N', '@IssueStartDate': 1120003200, '@ExRejectionAllowed': 'N', '@IssuedCapital': 999999999999.0, '@Token': 35000, '@ReadmissionDate': 0, '@LowPriceRange': 144550, '@DeleteFlag': 'N', '@Reserved1': None, '@Category': 1, '@ReservedD': None, '@ReservedB': None, '@ReservedC': None, '@ReservedA': None, '@TickSize': 5, '@NoDeliveryEndDate': 0, '@BoardLotQuantity': 25, '@Symbol': 'BANKNIFTY', '@Remarks': None, '@SymbolForAsset': None, '@Name': 'BANKNIFTY15SEP16800CE', '@FreezeQuantity': 2501.0, '@CheckSum': None, '@LocalLDBUpdateDateTime': 1121272656, '@MinimumLotQuantity': 25, '@PermittedToTrade': 0, '@ExpiryDate': 1127572200, '@NoDeliveryStartDate': 0, '@ExpulsionDate': 0, '@ListingDate': 1120003200, '@InstrumentName': 'OPTIDX', '@InstrumentOfAsset': None, '@ExDate': 0, '@IssueMaturityDate': 1127572200, '@ExerciseEndDate': 1127572200, '@CALevel': 0, '@InterestDivident': 0, '@RecordDate': 0, '@MarginPercentage': 0, '@EligibilityD': 0, '@EligibilityA': 1, '@EligibilityB': 0, '@EligibilityC': 0, '@Series': 'XX', '@AssetToken': 26009, '@MFAON': 0, '@SecurityStatusA': 1, '@SecurityStatusB': 2, '@SecurityStatusC': 2, '@SecurityStatusD': 3, '@HighPriceRange': 339510, '@StrikePrice': 1680000, '@CreditRating': None, '@RightsBonus': 0, '@ReservedIdentifier': 0, '@TickerSelection': 15, '@PlAllowed': 'N'} 运算符,但我为你清理了一点。

答案 3 :(得分:0)

正如EJK所说=是一个赋值运算符,但是在检查==时你甚至不需要booleans,所以请更新以匹配以下内容。

isASmoker = false!isASmoker

isMale = trueisMale