[英]How can I print out this array method that finds duplicates?
package Practice3;
import java.util.Arrays;
import java.util.Scanner;
public class ray1 {
public static int[] findDuplicates(int[] userInput)
{
for(int i = 0; i< userInput.length; i++)
{
for (int j = i+1; j < userInput.length; j++)
{
if(userInput[i]==(userInput[j]))
{
System.out.println(userInput[i]);
}
}
}
return userInput;
}
public static void main(String[] args)
{
int[] listOfNumbers = { 1, 2, 3, 4, 1, 2, 3, 1 };
int[] x = findDuplicates(listOfNumbers);
Arrays.sort(x);
System.out.println(Arrays.toString(x));
}
}
我認為問題可能出在 static void main 中,但我不太確定代碼有什么問題。
你返回你得到的輸入,所以你當然不會得到重復。 您應該在函數中創建一個哈希集並將重復項添加到其中。
public static void main(String[] args) {
int[] listOfNumbers = { 1, 2, 3, 4, 1, 2, 3, 1 };
ArrayList<Integer> list = new ArrayList<>(findDuplicates(listOfNumbers));
Collections.sort(list);
System.out.println(list);
}
public static HashSet<Integer> findDuplicates(int[] userInput) {
HashSet<Integer> output = new HashSet<Integer>();
for(int i = 0; i< userInput.length; i++) {
for (int j = i+1; j < userInput.length; j++) {
if(userInput[i]== userInput[j]) {
output.add(userInput[i]);
}
}
}
return output;
}
請注意,我使用返回類型作為 HashSet,它更合適,因為您希望每個重復項出現一次,然后我將其轉換為 ArrayList 並打印出來。
根據您的代碼, int[] listOfNumbers
和int[] x
是相同的。 您已將int[] listOfNumbers
傳遞給findDuplicates()
方法,並在不更改任何內容的情況下返回相同的內容。
如果您試圖刪除該方法中的重復項,那么您需要在循環中執行某些操作,在其中檢查value[i] == value[j] where i!=j
。
給您的一個建議是,當value[i] != value[j]
時嘗試將數字添加到Collection
,但當它們相似時則不然。
完成后,在兩個循環結束時,您將擁有一個帶有唯一編號的Collection
。 然后,您將能夠進行排序和打印。
注意:這不是最簡單或最佳的方法,因為 Java 有一個名為Set
的概念來收集唯一元素。 首先,如果您可以更改您的方法並弄清楚如何獲得這兩個循環以滿足要求,那就太好了。
我建議首先修復findDuplicates
方法來做它應該做的事情。 我的理解是它應該返回一個數組,其中包含在userInput
數組中出現多次的值。
一種方法可能是在findDuplicates
方法的開頭創建一個新數組,並將其命名為例如duplicatedValues
。 然后,您可以使用其余方法邏輯標識為重復的值填充它。 鑒於你的語句在你的意見之一是,輸出應為[ 1, 2, 3 ]
我想你也應該改變if
聲明只接受已經不是價值觀duplicatedValues
陣列,這甚至可能意味着3 for
環形。 否則, duplicatedValues
數組本身也將包含重復項。
當您使用“唯一重復項”填充duplicatedValues
數組時,您可以返回該數組而不是userInput
數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.