2013-03-14 51 views
0

這裏的問題是,當用戶輸入'-1'時,我們希望程序停止循環/停止詢問整數,它不必獲得我們陣列的最大長度停止詢問用戶輸入的循環

import java.util.Scanner; 
public class DELETE DUPLICATES { 
public static void main(String[] args) { 
     UserInput(); 
     getCopies(maxInput); 
     removeDuplicates(maxInput); 
} 
static int[] maxInput= new int[20]; 
static int[] copies = new int[20]; 
static int[] duplicate = new int[20]; 
//get user's input/s  
public static void UserInput() { 
    Scanner scan = new Scanner(System.in); 
     int integer = 0; 
     int i = 0; 
    System.out.println("Enter Numbers: "); 
     while(i < maxInput.length) 
     { 
       integer = scan.nextInt();   
       maxInput[i] = integer; 
         i++; 
         if (integer == -1) 
          break; 
     } 
        int j = 0; 
     for(int allInteger : maxInput) { 
       System.out.print(allInteger+ " "); 
       j++; 
     } 
} 
//to get value/number of copies of the duplicate number/s 
public static void getCopies(int[] Array) { 
    for(int allCopies : Array) { 
    copies[allCopies]++; 
} 

for(int k = 0; k < copies.length; k++) { 
    if(copies[k] > 1) { 
     System.out.print("\nValue " + k + " : " + copies[k] + " copies are detected"); 

    } 
     } 
     } 
//remove duplicates 
public static void removeDuplicates(int[] Array) { 
for(int removeCopies : Array) { 
    duplicate[removeCopies]++; 
    } 

    for(int a = 0; a < duplicate.length; a++) { 
     if(duplicate[a] >= 1) { 
      System.out.print("\n"+a); 

     } 
      } 
    } 
} 

示例: 如果我們輸入: -1

The result of our program is : 1 2 3 3 4 5 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 
We want the result to be like: 1 2 3 3 4 5 

我們需要你的幫助guyz。練我們的節目1主題,希望我們能找到這裏一些幫助

+0

陣列具有固定的大小。如果您想要一個可以更改大小的列表,請嘗試列表。 – 2013-03-14 05:35:39

+1

第一課:Java不是JavaScript。 – 2013-03-14 05:35:43

+0

'公共類DELETE DUPLICATES'這不會編譯!也遵循Java第一個字母大寫的信頭不是全部 – 2013-03-14 07:16:07

回答

1

你可以做以下變化只是打印所需的值:

for(int allInteger : maxInput) 
{ 
    if(allInteger == -1) 
     break; 

    System.out.print(allInteger+ " "); 
    j++; 
} 

但是,更好的變化是重新考慮你的設計和使用數據的結構。

0

maxInput數組的指定大小是20,所以它會有這個數字。的元素並打印int的默認值。

您可以使用列表,而不是和檢查大小爲最大輸入和退出循環

0

如果不這樣做需要使用數組,然後Collection有很多的優點。讓我們用一個List

static int maxInputCount = 20; 
static ArrayList<Integer> input= new ArrayList<>(); 

...

for (int i = 0; i < maxInputCount; i++) 
    { 
      integer = scan.nextInt(); 
      if (integer == -1) 
       break; 
      input.add(integer); 
    } 
    for(int integer : input) { 
      System.out.print(integer+ " "); 
    } 
+0

非常感謝你的幫助:))我們知道了:D – shiong 2013-03-14 05:53:47