我想比較兩個用戶定義的字符串並輸出兩個字符串之間共享字符的數量的計數,而不訴諸使用數組。然後我需要輸出每個字符。我理解使用掃描儀的用戶輸入部分,但事後我很無能。計數和輸出兩個字符串之間的像字符
例如, 「阻礙」 爲字符串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