2015-09-25 58 views
1

我有一個任務,使一個程序,它允許用戶輸入一個無限
直到0進入號,打印的最小和最大數量,並說,如果他們是奇怪的甚至是。的用戶輸入無限數量的

我很滿意除了如何讓用戶輸入儘可能多的數字和我不確定如何開始這一點。我應該使用循環還是其他方法?

請注意,我纔開始學習Java上週還有我unfamilliar與語言

非常感謝!

+0

循環是去的方式。提供一個特殊的輸入序列(例如詢問用戶是否要繼續,如果沒有結束,則開始下一次迭代)。 – Thomas

+0

循環。而是問你的教授/老師什麼是無限的意思。如果你沒有條件停止循環,你將有一個無限循環。 – SomeJavaGuy

回答

3

我對除了如何讓用戶輸入儘可能多的數字所需的任何東西都感到舒服,我不確定如何開始這一點。我應該使用循環還是其他方法?

由於這是一項功課,你可能不希望我們爲你做功課。這是你可以做什麼:

do{ 
    //prompt user for input 
    //prompt user to continue (y/n) 
    //if 'n' was given 
     //proceed = false; 
}while(proceed); 

您可以使用做,而循環。您現在可以提示用戶無限輸入,直到他們決定停止。


更新1:(根據問題的變化)

終止條件:是0時,輸入:

do{ 
    //prompt user for integer input 
    //if (input == 0) 
     //break; (exit loop) 
    //store input 
}while(input != 0); 
+0

謝謝我剛剛查看了文檔,看起來它應該用於此目的,謝謝 – Tom

+0

@Tom如果您有更多問題,可以將它留在評論中。 – user3437460

0

***試着做你自己使用此僅供參考。

我知道它是不正確的,因爲它是爲你的任務而放棄的代碼。只要你沒有得到輸出,就使用(理解和學習)這個。

 int n=0,temp=0,z=0,i=0,j=0; 
     int []a=new int[1000]; //as size is not given by user assign the array with a much greater value 

     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Object for BufferedReader class used for reading elements 

     do{ 
      System.out.print("Enter the number:"); 
      a[n]=Integer.parseInt(br.readLine()); //String to integer conversion 
      n++; 
      System.out.println("Do you want to enter more numbers(0/1):"); 
      z=Integer.parseInt(br.readLine()); 
     }while(z!=0); 


     //Sorting 
     for(i=0;i<n;i++){ 
      for(j=i+1;j<n;j++){ 
       if(a[i]>a[j]) 
       {  
        temp=a[i]; 
        a[i]=a[j]; 
        a[j]=temp; 
       } 
      } 
     } 

     //Now after sorting the smallest number will be in the first location ie; 
     //"0" so inorder to check it is even or odd we take check its remainder when it is divided by 2. 
     if(a[0]%2==0){ 
      System.out.println("The smallest number is : "+ a[0] + " & the number is even");} 
     else{ 
      System.out.println("The smallest number is : "+ a[0] + " & the number is odd");} 

     if(a[n-1]%2==0){ 
      System.out.println("The largest number is : "+ a[n-1] + " & the number is even");} 
     else{ 
      System.out.println("The largest number is : "+ a[n-1] + " & the number is odd");} 

樣品輸出如下:

Sample Output

+0

感謝您提供這樣一個全面的答案!我必須承認,在這一點上,我所使用的一些概念和項目已經超出了我的視野,但這對我來說是一個很好的學習工具,所以謝謝! :) – Tom