我想比较两个用户定义的字符串并输出两个字符串之间共享字符的数量的计数,而不诉诸使用数组。然后我需要输出每个字符。我理解使用扫描仪的用户输入部分,但事后我很无能。计数和输出两个字符串之间的像字符
例如, “阻碍” 为字符串1,和 “发生” 为字符串2将返回:
数共享字符数= 5
共享字符>> “H”, “一个”,“P的“,”p“,”e“,”e“
这是我到目前为止。尽管它在单独的行上打印每个字符。有没有阵列将它们全部列在上面的一行上的方法?:
public class CountMatches {
public static void main(String[] args)
{
//Declare both Strings.
String word1;
String word2;
int count = 0;
//Call for User Input.
Scanner inputDevice = new Scanner(System.in);
System.out.print("Input String 1 >> ");
word1 = inputDevice.next();
System.out.print("Input String 2 >> ");
word2 = inputDevice.next();
inputDevice.close();
//Determine lengths and set label accordingly.
String BigWord;
String SmallWord;
if (word1.length() > word2.length())
{
BigWord = word1;
SmallWord = word2;
}
else
{
BigWord = word2;
SmallWord = word1;
}
//Count and Display the like characters.
for (int i = 0; i < SmallWord.length(); i++)
{
if (BigWord.contains(String.valueOf(SmallWord.charAt(i))))
{
System.out.println("both words contain the letter " + SmallWord.charAt(i));
count++;
}
}
//Display the count of like characters.
System.out.print("Number of like characters >> " + count);
}
}
这实际上是错误的,因为当你迭代较小的长度时,你认为word2是包含子句中较短的一个。如果你让word1 =“bbb”和word2 =“aaab”,它会说他们没有共同的字母。 – mau
你是正确的,需要修改,但原因稍有不同。称它为“错误”是不准确的(因为它可以用于许多输入)和一些苛刻的哈哈。做了一个编辑。请验证它。欣赏反馈。有了这样的东西,我很可能犯下愚蠢的错误。 – Vidya
是的,错误的说法不好。小逻辑错误更好:)。这现在起作用。 – mau