public static void main(String[] args) {
String str = "XXYZZA";
char[] a = str.toCharArray();
int count=0;
for (int i = 0; i < a.length; i++)
{
if (a[i] == a[i++])
{
count++;
}
else
System.out.println(a[i++]);
}
}“否则”部分中的print语句未被执行。所需的输出应该是
Y
A发布于 2018-06-12 05:37:26
好的,首先,也是最重要的,正确的缩进,帮助我们理解代码.
其次,由于两个原因,if (a[i] == a[i++])并不是正确的选择。
a.length - 1的最大值,您的测试条件i++将尝试访问索引 a.length中的元素,正如您可能已经猜到的那样,该元素并不存在。您需要的是某种排序算法,而不需要实际保存排序序列。
发布于 2018-06-12 05:37:28
就像这样,也许能帮到你
public static void main(String[] args) {
String str = "XXYZZA";
char[] a = str.toCharArray();
HashSet<Character> set = new HashSet<>();
set.add( a[0]);
for (int i = 1; i < a.length; i++)
{
if (!set.contains(a[i]) && (i+1 == a.length || a[i] != a[i+1]))
{
System.out.println(a[i]);
}
set.add(a[i]);
}https://stackoverflow.com/questions/50809676
复制相似问题