简体   繁体   English

为什么不能在简短的IF语句中进行条件赋值?

[英]Why can't you make conditional assignment in short hand IF statement?

I'm trying to update softcount for my Blackjack game to account for Aces being played (value 11 or 1). 我正在尝试为我的二十一点游戏更新软计数,以说明正在播放的Ace(值11或1)。 When using the short-form IF statement, why is the first line of code incorrect, but the second line is okay to use? 使用简短的IF语句时,为什么第一行代码不正确,但是第二行可以使用? Is this type of if statement limited? 这种if语句是否受限制?

(counter > 1) ? (softcount+=1) : (softcount+=value); // bad


softcount += (counter > 1) ? 1 : value; // good

The ternary has to be seen as a way to evaluate something and not as a way to apply a processing. 三元必须被视为一种评估某种事物的方式,而不是一种应用处理的方式。
So it expects some expressions after ? 所以它期望之后有一些表达式? but you wrote statements : softcount+=1 and (softcount+=value) in the first code. 但是您在第一个代码中写了语句: softcount+=1(softcount+=value)
In the second code, it is ok because you specified two expressions : 1 and value . 在第二个代码中,可以,因为您指定了两个表达式: 1value

Besides do you really find this code a short hand ? 此外,您是否真的觉得此代码简而言之?

(counter > 1) ? (softcount+=1) : (softcount+=value); // bad

You repeat the increment part. 您重复增量部分。

What you want in your case is just : 您所需要的只是:

if (counter > 1) { softcount+=1;} else {softcount+=value;)

It is simply how the language is defined. 这只是语言的定义方式。

Only certain expressions - statement expressions - can be made into a statement by adding ; 通过添加;只能将某些表达式(语句表达式)制成语句; . (Statement expression + ; is an expression statement ). (语句表达式+ ;是一个表达式语句 )。

From JLS Sec 14.8 : JLS Sec 14.8开始

ExpressionStatement:
  StatementExpression ;

StatementExpression:
  Assignment 
  PreIncrementExpression 
  PreDecrementExpression 
  PostIncrementExpression 
  PostDecrementExpression 
  MethodInvocation 
  ClassInstanceCreationExpression

Conditional expressions are not statement expressions. 条件表达式不是语句表达式。

It is called ternary operator, it is used when you simply want to return a value based on condition. 它称为三元运算符,仅在您想根据条件返回值时使用。 It's main purpose is to avoid if else for simple avaluations. 它的主要目的是避免进行简单评估。 In your case you should use if else. 在您的情况下,应使用if else。

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

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