java - finding the index of the largest element in an array -


i want write code returns index of largest element in given array. however, when try compiling, message can't seem understand. although have done things error message tells, keeps telling me fix them. please novice programmer!


public class largest {     int[] array = new int[10];     array[0] = 100;     array[1] = 200;     array[2] = 300;     array[3] = 400;     array[4] = 500;     array[5] = 600;     array[6] = 700;     array[7] = 800;     array[8] = 900;     array[9] = 1000;     int index;      public static void main(string args) {          (int i=0; i<10; i++) {             if (array[i] < array[i+1]) {                 index = + 1;             } else {                 index = i;             }             i++;         }         system.out.println(index);     } } 

and below compilation message.


largest.java:3: error: ']' expected     array[0] = 100;       ^ largest.java:3: error: ';' expected     array[0] = 100;        ^ largest.java:3: error: illegal start of type     array[0] = 100;          ^ largest.java:3: error: <identifier> expected     array[0] = 100;           ^ 

and continues indices.

this type of initialization can't done outside of method :

array[0] = 100; array[1] = 200; array[2] = 300; array[3] = 400; array[4] = 500; array[5] = 600; array[6] = 700; array[7] = 800; array[8] = 900; array[9] = 1000; 

either move assignments main of change to

int[] array = new int[10]; 

to

int[] array = {100,200,300,400,500,600,700,800,900,1000}; 

btw, in addition compilation error, code doesn't supposed do. throw arrayindexoutofboundsexception (since array[i+1] out of bounds when reaches 9). in order find index of largest element must maintain variable holding current maximum , compare elements of array.

public static void main(string args) {     int max = array[0];     index = 0;     (int i=1; i<10; i++) {         if (array[i] > max) {             index = i;             max = array[i];         }     }     system.out.println(index); } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -