Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

Why doesn't this method work? Java ternary operator

What's wrong with this code:

void bark(boolean hamlet) {
    hamlet ? System.out.println("To Bark.") : System.out.println("Not to Bark");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ternary operators can't have statements that don't return values, void methods. You need statements that have return values.

You need to rewrite it.

void bark(boolean hamlet) {
     System.out.println( hamlet ? "To Bark." : "Not to Bark" );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...