标签: conditional-operator

Java条件运算符中的可选项导致NullPointerException

我有一个包含两个参数的Dto的List <>:type和value.现在我想找到类型为"C"的列表中的一个元素并读出该值.

执行以下java代码时,我得到一个我不明白的NullPointerException:

class TestDto
{
    private String type;
    private Double value;

    TestDto(final String type, final Double value)
    {
        this.type = type;
        this.value = value;
    }

    public String getType() { return type; }
    public Double getValue() { return value; }
}
Run Code Online (Sandbox Code Playgroud)

...

List<TestDto> testList = new ArrayList<>();
testList.add(new TestDto("A", 11.111d));
testList.add(new TestDto("B", 22.222d));
testList.add(new TestDto("C", null));

Predicate<TestDto> typePredicate = c-> c.getType().equals("C");
Optional optional = testList.stream().filter(typePredicate).findFirst();

if(optional.isPresent()){
    System.out.println("if-output = " + ((TestDto) optional.get()).getValue());
}

Double value = optional.isPresent() ? ((TestDto) optional.get()).getValue() …
Run Code Online (Sandbox Code Playgroud)

java nullpointerexception conditional-operator optional

4
推荐指数
1
解决办法
738
查看次数

如何使用三元运算符制作指向多态类的唯一指针?

我正在尝试使用三元运算符设置变量。但是,编译器抱怨类型不兼容。我确定有办法做到这一点。我已尝试对基类进行静态转换,但无法获得正确的语法。

#include <iostream>
#include <memory>
struct A
{
    virtual ~A() = default;
    virtual void test() {std::cout << "A" << std::endl;} 
};

struct B: public A
{
    void test() final {std::cout << "B" << std::endl;} 
};

struct C: public A
{
    void test() final {std::cout << "C" << std::endl;} 
};

int main()
{
    bool t = true;
    // Try to cast try a base unique class ptr. Maybe use static_cast??
    std::unique_ptr<A> aptr = t ? std::make_unique<B>(): std::make_unique<C>();
    aptr->test();
}
Run Code Online (Sandbox Code Playgroud)

c++ conditional-operator c++11 c++14

4
推荐指数
1
解决办法
352
查看次数

C++ 中的条件运算符 ( ? : ) 可以是编译时吗?

三元(条件)运算符可以用作类似于constexpr if()C++17 中引入的 , 吗?

我想为模板中的成员变量初始化添加一些条件。以下表达式会在编译时或运行时解析吗?如果是这样,是否有任何其他运算符可以在编译时解析,从而可以避免模板特化?

template<int a>
struct hello {
    constexpr static int n = (a != 0) ? 10 : 20;
}
Run Code Online (Sandbox Code Playgroud)

c++ conditional-operator compile-time-constant compile-time c++17

4
推荐指数
1
解决办法
306
查看次数

视图体中的swiftui三元运算符

在 swiftyui 主体内,基于 news.urlToImage 值,我需要能够加载另一个视图(LOadRemoteImageView,这只是另一个接受可选 url 字符串来加载远程图像的视图),或者显示一个文本字符串“没有图片网址”。

按照下面的语法,它工作正常

if news.urlToImage == nil {
Text("no image url")
}else {
    LoadRemoteImageView(withURL: news.urlToImage!).frame(width: 140, height: 140)
}
Run Code Online (Sandbox Code Playgroud)

然而,当尝试内联代码时,它失败了,intellisense 没有正确的错误消息

news.urlToImage == nil ? Text("no image") : LoadRemoteImageView(withURL: news.urlToImage!)
Run Code Online (Sandbox Code Playgroud)

如果 urlToImage: String 不是 nil,也尝试使用 map 来显示两个视图中的任何一个,但也失败了

news.urlToImage.map {
$0 != nil ? LoadRemoteImageView(withURL: $0) : Text("no image")
Run Code Online (Sandbox Code Playgroud)

}

conditional-operator swift swiftui

4
推荐指数
1
解决办法
1446
查看次数

C++中三元运算符的意外行为

以下是我编写的代码片段:

int n,i,j;
map<int,int>mp;
vector<int>vec;
cin>>n;
for(i=0; i<n; i++)
{
    cin>>j;
    mp[j]==0? mp[j]=1,vec.push_back(j): mp[j]=1;
}
Run Code Online (Sandbox Code Playgroud)

对于for循环内的第二行,CodeBlocks-16.01 版本显示以下错误:

second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'
Run Code Online (Sandbox Code Playgroud)

但是当我将行更改为:

second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'
Run Code Online (Sandbox Code Playgroud)

没有错误。以下行有什么问题?

mp[j]==0? vec.push_back(j), mp[j]=1: mp[j]=1;
Run Code Online (Sandbox Code Playgroud)

c++ conditional-operator

4
推荐指数
1
解决办法
75
查看次数

带有三元运算符的 Walrus 运算符的正确语法是什么?

看看Python-DevStackOverflow,Python 的三元运算符等价物是:

a if condition else b
Run Code Online (Sandbox Code Playgroud)

看看PEP-572StackOverflow,我明白了 Walrus 算子是什么:

:=
Run Code Online (Sandbox Code Playgroud)

现在我试图将“海象运算符的赋值”和“三元运算符的条件检查”组合成一个语句,例如:

other_func(a) if (a := some_func(some_input)) else b
Run Code Online (Sandbox Code Playgroud)

例如,请考虑以下代码段:

do_something(list_of_roles) if list_of_roles := get_role_list(username) else "Role list is [] empty"
Run Code Online (Sandbox Code Playgroud)

我无法理解语法。尝试了各种组合后,每次解释器抛出SyntaxError: invalid syntax. 我的 python 版本是 3.8.3。

我的问题是在三元运算符中嵌入海象运算符的正确语法什么?

python conditional-operator python-3.x walrus-operator

4
推荐指数
2
解决办法
1302
查看次数

为什么这个三元会导致打印指针?

这个三元,当按原样使用时,会吐出一个指针:

std::stringstream ss;
ss << pair.second ? pair.second->toString() : "null";
std::cout << ss.str() << '\n';
Run Code Online (Sandbox Code Playgroud)

这是一个示例输出:

{
        "glossary": 000002B96B321F48
}
Run Code Online (Sandbox Code Playgroud)

但是,当我将三元运算符括在括号中时,它可以正常工作并为我提供 toString() 或“null”的内容。

ss << (pair.second ? pair.second->toString() : "null");
Run Code Online (Sandbox Code Playgroud)

此外,将其扩展为适当的 if/else 也可以修复它:

if (pair.second)
{
    ss << pair.second->toString();
}
else
{
    ss << "null";
}
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

c++ conditional-operator

4
推荐指数
2
解决办法
113
查看次数

JavaScript - 为什么包含括号会导致三元表达式出错?

我有以下代码:

const showMessage = msg => console.log(msg);

let person = {
  firstName: `Mick`,
  lastName: `McCarthy`,
  firstTimeUser: true
}

(person.firstTimeUser === true) ? showMessage(`Welcome, ${person.firstName}!`): showMessage(`Glad you're back, ${person.firstName}!`)
Run Code Online (Sandbox Code Playgroud)

这导致错误:

home.js:7 Uncaught ReferenceError: Cannot access 'person' before initialization
    at home.js:7
Run Code Online (Sandbox Code Playgroud)

但是,在以下情况下(三元表达式中的括号已被删除):

home.js:7 Uncaught ReferenceError: Cannot access 'person' before initialization
    at home.js:7
Run Code Online (Sandbox Code Playgroud)

没有错误,欢迎信息显示正确。

为什么会这样?我的印象是括号在三元表达式中是可选的。我想,这是什么做的计算顺序,但由于三元表达式是在不同的线路let person = {...,我不清楚为什么发生这种情况。

事实上,在我正在学习的 JavaScript 课程展示的示例中,讲师展示了以下示例,无论是否带括号都可以完美运行:

let price = 20

(price < 10) ? showMessage('yes') : showMessage('no')
Run Code Online (Sandbox Code Playgroud)

但是,当我在自己的机器上尝试时,出现了同样的问题。他们是否可以使用行为不同的旧版 JavaScript?如果有,发生了什么变化?

非常感谢!

javascript conditional-operator operator-precedence

4
推荐指数
1
解决办法
64
查看次数

如何在 next.js 的数组映射函数中使用 if 语句

如果索引号的余数为0,我想包装我需要在下面和下面显示的代码。我怎样才能做到这一点?我尝试了下面的方法,但没有成功。我收到语法错误。

{索引%3==0?...:...}

{索引% 3 == 0 && ...}

export default function UserPosts() {
    // some code...
    return (
        <div className={styles.userPosts}>
            {postsList.map((post, index) => {
                return (
                    if (index % 3 == 0) {
                        <div className={styles.userPostsRow}>
                    }
                    <div className={styles.userPostWrapper}>
                        <div className={styles.userPostColumn}>
                            <Link href={`/${username}`}>
                                <a>
                                    <div className={styles.userPost}>
                                        <img src={post.image} alt="" />
                                    </div>
                                </a>
                            </Link>
                        </div>
                    </div>
                    if (index % 3 == 0) {
                        </div>
                    }
                )                
            })}
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

javascript conditional-operator jsx reactjs next.js

4
推荐指数
2
解决办法
3万
查看次数

Bash 条件表达式 (-v) 检查变量是否已设置

当尝试检查 bash 中是否设置或取消设置变量时,我发现了 bash 条件表达式:(-v此处如果设置了 shell 变量(已分配值),则为 True。)。我尝试代码:

#!/bin/bash
VAR="not-empty"
if [ ! -v "$VAR" ]; then
        echo "unset"
else 
        echo "set: $VAR"
fi
Run Code Online (Sandbox Code Playgroud)

但是,输出甚至是在代码开头unset分配的。VAR

我发现如何检查 Bash 中是否设置了变量?问题,并尝试替换! -v-z检查字符串变量VAR。输出是set: non-empty.

任何人都可以帮助解释第一种情况(使用-v表达式)为什么输出是unset

我的 bash 版本:

GNU bash,版本 5.0.17(1)-release (x86_64-pc-linux-gnu) 版权所有 (C) 2019 Free Software Foundation, Inc. 许可证 GPLv3+:GNU GPL 版本 3 或更高版本http://gnu.org/licenses /gpl.html

linux bash conditional-operator

4
推荐指数
1
解决办法
1万
查看次数