2015-05-29 62 views
-1

我想從用戶讀取n個值,但我不知道n的值。第二種情況{11,22,77,43,2,1,2111,322} 假設我想讀取10個整數來自用戶的值(第二次5 int int 值)(取決於每種情況)。在不知道n值的情況下獲取用戶輸入的n值

第二件事是我想將這個值存儲在一個數組中。

我真的被這個困住了。 任何幫助?

我嘗試以下代碼 -

int a[50],i=-1;//how to dynamically assign memory to an array 
Scanner s=new Scanner(System.in); 
do{ 
    a[++i]=s.nextInt(); 
}while(!hasNextLine()); 
+2

爲什麼不向用戶詢問數字並將其分配給可用作數組大小的最終變量? –

+0

其實這是面試問題先生。我正在爲它做準備。問題在不知道n值的情況下給出。 –

+0

如果n未知,那麼您需要一個動態大小的集合,如List。 –

回答

-1

試試這個:

import java.io.*; 

public class Hey 

{ 
    public static void main(String ar[])throws IOException 
    { 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     String input = "";//get the input 
     while((input = br.readLine()) != null) 
      { 
       String []numbers = input.split(","); 
       System.out.println(numbers.length); 
      } 
    } 
} 

Look at this

+0

'while(T - != 0)'?爲什麼'T - '? – Gosu

+0

T是測試用例的數量。 –

+0

我不知道要在該數組中存儲多少值?這段代碼不是我的問題的答案 –

-2

如何爲用戶打算指示輸入已完成?輸入的格式如何? 我想:

  • 用戶輸入一個整數爲每行或由空格分隔的整數列表。
  • 用戶輸入一個空行或與Intege不同的東西表示它已完成。

您需要一個ArrayList,因爲在開始請求輸入之前您不知道輸入的數量。 ArrayList是動態的,所以你可以添加內容到它之前沒有聲明它的大小。

Scanner s = new Scanner(System.in); 
ArrayList<Integer> list = new ArrayList<>(); 
while(s.hasNextInt()){ 

    list.add(s.nextInt()); 

} 
2

根據我的理解使用這個。

public static void main(String[] args){ 
     int a[] = null; 
     int i = 1; 
     Scanner s=new Scanner(System.in); 
     while (s.hasNextLine()){ 
      int temp[] = null; 
      if(a!=null){ 
       temp = a; 
      } 
      a = new int[i]; 
      a[i-1]=s.nextInt();   
      if(temp!= null){ 
       for(int j=0;j<temp.length;j++){ 
       a[j]=temp[j]; 
       } 

      } 
      i++; 
     } 

    } 
+0

什麼時候while循環終止? –

+0

如果沒有輸入。 –

相關問題