三元运算符不是语句

Ternary operator is not a statement

我有以下三元表达式:

((!f.exists()) ? (f.createNewFile() ? printFile() : throw new Exception("Error in creating file")) : printFile());

由于一个或多个我不知道的原因 IDE 告诉我这不是一个声明。为什么?

您似乎是将其用作语句而不是赋值

From what SO says it is not possible to do so

Also from another SO Articel, that says you can´t throw an exception in the ternary statement

我认为你需要回到像这样的 if-else 子句:

if (!f.exists()) {
   try {
      f.createNewFile();
      printFile();
   } catch(Exception e ) {
      System.out.println("Error in creating file");
   }
} else {
   printFile();
}

这是无效的,您需要return一个值

printFile() : throw new Exception("Error in creating file")

试试这个

if(f.exists() || f.createNewFile()) {
  printFile();
}else{
  throw new Exception("Error in creating file");
}

"COND ? Statement : Statement" 构造是一个表达式。它不能用作语句。 如果没有赋值,它可以用于在函数调用或字符串连接中解析条件参数等情况。

Func( (COND ? param1 : param2) );
"Hi"+(con?"Miss":"Mr.")+"";

三元运算符中的语句需要非空。他们需要 return 一些东西。

示例:

  • 考虑一个案例,其中 count 变量递增,我正在检查它的值和 return 高于特定阈值的真或假。
  • System.out.println((count >10 ? true: false));
  • 相比之下,count >10 ? true: false 编译器会抱怨这不是一个语句。