Read integer array through white space with using limit in java -
my requirement is:
the first line of input consists of integer n (where n>=3) denotes size of array. in next line there n integers separated space correspond n elements in array. have used below code:
scanner length = new scanner(system.in); system.out.println("please enter length of aarry:"); int n=length.nextint(); int[] numbers = new int[n]; scanner sc = new scanner(system.in); system.out.println("enter elements seperated spaces: "); string input = sc.nextline(); stringtokenizer strtoken = new stringtokenizer(input); int count = strtoken.counttokens(); //reads in numbers array system.out.println("count: " + n); int[] arr = new int[n]; for(int x = 0;x < n;x++){ arr[x] = integer.parseint((string)strtoken.nextelement()); system.out.println("values are: " + arr[x]); }
but problem : above code read correctly integers entered white space specify limit entering values .please me how achieve this.
there several ways address 'issue':
- easiest: don't ask length of array => length = #tokens
- validate:
if (n != count) system.err.println("invalid input...")
Comments
Post a Comment