Java 如何检查字符串是否具有相同的字符

Java 如何检查字符串是否具有相同的字符,java,Java,例如: Input=zzzz Output=true Input=zaqz Output=false 如果可能的话,它能在没有If-else语句的情况下运行吗?一个简单的迭代就足够了 String s = /* input string */; char[] chars = s.toCharArray(); boolean samesies = chars.length > 0; //initial value //see: ternary statements char init =

例如:

Input=zzzz Output=true
Input=zaqz Output=false

如果可能的话,它能在没有If-else语句的情况下运行吗?

一个简单的迭代就足够了

String s = /* input string */;
char[] chars = s.toCharArray();
boolean samesies = chars.length > 0; //initial value
//see: ternary statements
char init = samesies ? chars[0] : 0; //get the first element, or the null character for an empty string
for (int i = 1; samesies && i < chars.length; i++) {
    if (chars[i] != init) {
        samesies = false;
        break; //optional, but can replace the "samesies &&" in your for statement
    }
}
//"samesies" has the appropriate value now
您所能做的最好的事情就是向我们展示您所做的尝试,因为对您自己的代码的评论可以帮助您以您阅读的方式查看定义的问题

public class Main {
    public static void main(String[] args) {
        System.out.println("zzzz".chars().distinct().count() == 1);
        System.out.println("zaqz".chars().distinct().count() == 1);
    }
}
输出:


为什么没有if/else?@HarshalParekh Bob叔叔的干净代码原则说,如果你能避免if/else,你一定要这样做。@UladzislauKaminski,我的问题是关于OP的。此外,问题中没有提到这个原则。OP可能是初学者,甚至可能被误导。@HarshalParekh绝对同意你的观点。试着猜猜halium是什么意思这看起来太夸张了。您可以简单地使用正则表达式,例如string.matches。\\1+答案的要点是只使用语言循环/数组的基本知识来回答,而不是使用最少行的代码。我不确定OP对语言有多新,但我想它超出了使用regex lookarounds的范围。如果您想要简洁,请参阅Avinash的答案,以获得完全可接受的解决方案。
public class Main {
    public static void main(String[] args) {
        System.out.println("zzzz".chars().distinct().count() == 1);
        System.out.println("zaqz".chars().distinct().count() == 1);
    }
}
true
false
import java.io.*;

public class Checker {
    public static void main(String[] args) throws Exception {
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        String s = read.readLine();
        boolean res = s.chars().distinct().count() == 1;
        System.out.println(res);
    }
}