在Java中的条件运算符,我不希望假的布尔值执行任何操作。

huangapple go评论72阅读模式
英文:

Conditional Operator in Java where I don't want the false Boolean to do anything

问题

我是一个极其初学的编程学生,正在学习Java编程。

在一个作业的一部分中,我有一个 for 循环,在一个字符串中查找特定的字符,如果找到了那个字符,它需要更新我稍后代码部分需要用到的计数器。根据这个作业的要求,我们只能使用 条件(三元)运算符。我已经能够使用 if 语句完成代码,但是正如我所说的,我需要使用条件运算符。

有没有办法让条件运算符的假语句什么都不做?或者我应该让它更新一些无关紧要的垃圾变量?

这个代码有效

if (someString.charAt(i) == someChar) {
    someInt++;
}

但是我尝试让下面的代码工作

someString.charAt(i) == someChar ? someInt++ : 在这里填写什么;
英文:

I am a extremely beginner programming student working with Java.

For a section of an assignment I have a for loop that looks for a specific character in a string, and if it finds that character, it needs to update my count for a later section of the code. For this particular assignment, we are required to only use the conditional (ternary) operator. I have been able to complete the code using an if statement, but like I said, I need to use a conditional operator.

Is there a way for the false statement from a conditional operator to do nothing? Or should I have it update some garbage variable that doesn't matter instead?

This works

if (someString.charAt(i) == someChar) {
    someInt++;
}

But trying to get this working

someString.charAt(i) == someChar ? someInt++ : (this right here);

答案1

得分: 0

也许类似这样的代码可以帮助?

    public int answer(String input, char match) {
        int counter = 0;
        for (final char character : input.toCharArray()) {
            counter += character == match ? 1 : 0;
        }
        return counter;
    }
英文:

Maybe something like this can help?

    public int answer(String input, char match) {
        int counter = 0;
        for (final char character : input.toCharArray()) {
            counter += character == match ? 1 : 0;
        }
        return counter;
    }

答案2

得分: 0

public static int count(String str, char ch) {
    return str.isEmpty() ? 0 : (str.charAt(0) == ch ? 1 : 0) + count(str.substring(1), ch);
}
英文:
public static int count(String str, char ch) {
    return str.isEmpty() ? 0 : (str.charAt(0) == ch ? 1 : 0) + count(str.substring(1), ch);
}

huangapple
  • 本文由 发表于 2020年10月19日 06:03:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64418782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定