2015-12-28 47 views
0

我知道這不是你應該做的事情,但我仍然試圖找出一種方法來運行這個循環,讓arr[i]內部它「知道」數組中元素數量的增加(我在循環之外聲明,因爲我不希望它每次都創建一個新元素)。通過輸入他們未知的元素創建數組

int counter=1, note=0; 

    System.out.println("Please enter characters, -1 to stop: "); 

    do { 
     char[] arr= new char[counter]; 
     for (int i=0;i<=counter;i++){ 

      arr[i] = s.next().charAt(0); 
      if (arr[i]==-1){ 
       note = -1;     
       break; 
      } 
      ++counter; 
     } 
    } while (note>=0); 
+0

你是什麼意思?....讓它更清楚。 –

+0

'我<= counter'會給你一個'ArrayIndexOutOfBoundsException'。另外,在'for'循環中遞增'counter'將會使它成爲一個無限循環,除非'counter'爲0.到底是什麼意思?你知道你正在使用它作爲字符代碼,對吧? – bcsb1001

+0

感謝您的編輯。用戶將輸入一個未知的字符,並輸入-1停止,例如我將輸入abcd -1,我想要它做的是輸入a,b,c,d作爲數組的元素(while統計元素的數量),並在輸入-1時停止這樣做。 – Evi

回答

0

從你更清晰的評論,這是一個例子主要方法。

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); // Input 
    int amt = 0; // Amount of chars received 
    List<Character> chars = new ArrayList<>(); // ArrayList is easier for now 
    while (input.hasNext()) { // Grabs Strings separated by whitespaces 
     String token = input.next(); // Grab token 
     if (token.equals("-1")) { 
      break; // End if -1 is received 
     } else if (token.length() != 1) { 
      throw new IllegalArgumentException("Token not one char: " + token); 
      // It seems you want only chars - this handles wrong input 
     } else { 
      chars.add(token.charAt(0)); // Adds the character to the list 
      amt++; // Increment amt 
     } 
    } 
    char[] array = new char[amt]; // Converting to an array 
    for (int i = 0; i < amt; i++) { 
     array[i] = chars.get(i); // Copies chars into array 
    } 
    System.out.println(Arrays.toString(array)); // Handle data here 
} 

我希望這是正確的。 a b c d -1的輸入導致[a, b, c, d]的輸出。

0

如果您使用輸入字符串大小檢查,我認爲你會得到解決。

int counter=0, note=0; 

System.out.println("Please enter characters, -1 to stop: "); 
String input=s.nextLine(); 
counter=input.length(); 


char[] arr= new char[counter]; 
for (int i=0;i<counter;i++){ 
    arr[i] = input.charAt(i);   
} 

如果您使用的是ArrayList而不是Array,則無需擔心大小。

ArrayList是有效的靈活數據 原因使用add函數。

相關問題