所以我有这个任务,我必须输入两个字符串,然后我必须找到常见的字母,然后把它们写出来,但只写一次..所以举个例子 如果 string1 是“拟声词”而 string2 是“对话”,我应该返回: o,n,a,t,e,i...我唯一的问题是最后一部分(“我不知道如何只写一次字母)
这是我的代码
import java.util.Scanner;
import java.util.Arrays;
public class Zadatak4 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char niz[] = new char[100];
char niz2[] = new char[100];
System.out.print("Add the first string: ");
niz = scan.nextLine().toCharArray();
System.out.print("Add the second string: ");
niz2 = scan.nextLine().toCharArray();
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz2.length; j++) {
if (niz[i] == niz2[j]) {
System.out.println(niz[i] + " ");
// What now!?!?!?
}
}
}
}
}
最佳答案
使用集合:
LinkedHashSet<string> printNum = new LinkedHashSet<string>();
if(niz[i] == niz2[j])
{
printNum.add( niz[i] );
}
// outside of loop
for( string s : printNum )
{
System.out.println(s);
}
关于java - 如何只打印某些字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17241381/