[英]Java program to print first nonrepeating character in a string
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++]);
}
}
the print statement in the "else" part is not being executed. 未执行“其他”部分中的打印语句。 the desired output should be
所需的输出应该是
Y
A
Ok, first and for-most, proper indentations please, helps out a lot to understand the code. 好吧,首先也是最重要的一点是,适当的缩进,对理解代码有很大帮助。
Secondly, if (a[i] == a[i++])
is not the right way to go because of 2 reasons 其次,由于两个原因,
if (a[i] == a[i++])
不是正确的方法
a.length - 1
your test condition i++
will try to access the element at index a.length
, which, as you might have guessed it, does not exist. a.length - 1
最大值a.length - 1
您的测试条件i++
就会尝试访问索引 a.length
的元素,您可能已经猜到它不存在。 What you need is some sort of sorting algorithm without actually saving the sorted sequence. 您需要的是某种排序算法,而无需实际保存排序的序列。
Try like this, may help you 这样尝试,可能对您有帮助
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.