Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array using a while loop

Tags:

java

arrays

I have to:

  • create this java array;
  • loop through it using a while loop;
  • terminate the program if the sum adds up to 100;
  • and print the sum and the numbers that I did put into the array.

I can't figure out how to do that, here is my code so far, any help would be appreciated.

public class december2012 {
    public static void main(String[] args) {  

        int sum=0;            

        Scanner input = new Scanner(System.in);            

        int i=1;

        int [] array = new int[i];

        while( i > array.length || sum <= 100) {

          System.out.println("Write in the " + i + " number") ; 
          array[i]=input.nextInt();
          sum=+array[i];
           System.out.println("sum is " + sum); 

        }            

        }
    }
like image 717
user1534779 Avatar asked Jul 26 '26 12:07

user1534779


1 Answers

int i = 0;                            // array starts from 0
int [] array = new int[100];          // create larger array
while(i < array.length && sum <= 100) // i should be less then length
                                      // && instead of ||
{
   System.out.println("Write in the " + i + " number") ; 
   array[i] = input.nextInt();
   sum += array[i];                   // += instead of =+
   System.out.println("sum is " + sum);
   i++;                               // increment i 
}  

Ideone DEMO

like image 131
Ilya Avatar answered Jul 28 '26 01:07

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!