java - Array variable input help [close] -


first of all, have create array of length n, input variables fill array, @ array location k, have push arrays location k , 1 , put value of x array location k. if k = n, put x in n+1.

first of all, having problem making ints k , x work. reason code sets n first input , sets k , x same n when n set.

secondly, having trouble extending array n+1. know don't give me answer need direction on go.

import java.util.scanner; public class hw2 {    public static void main(string[] args)     {     scanner scan = new scanner(system.in);     int n = scan.nextint();     int k = scan.nextint();     int x = scan.nextint();     int[] = new int[n];     for(int = 0; i<n; i++)     {      a[i] = scan.nextint();     }     n++;     final int length = a.length - 1;     for(int j=length; j>k; j--)     {      a[j] = a[j-1];     }     a[k] = x;     for(int h = 0; h < n; h++)     {      system.out.println("location " + h + " " + a[h]);         }     } } 

sample input n k x a[0]... a[n-1] is

5  3  7  2  3  5  11  13 

respectively.

after code runs input, n should = 6 , array should be

a[0] = 2 a[1] = 3 a[2] = 5 a[3] = 7 a[4] = 11 a[5] = 13 

edit: read problem wrong. hint @ bottom said "assume array of @ least size n+1" ...

it looks including fine:

import java.util.scanner; public class hw2 {    public static void main(string[] args)     {     scanner scan = new scanner(system.in);     int n = scan.nextint();     int k = scan.nextint();     int x = scan.nextint();     int[] = new int[n];     for(int = 0; i<n; i++)     {      a[i] = scan.nextint();     } 

after gets little sketchy. problem interpreted couple ways...

then @ array location k, input variable x. if k = n, put x in n+1

to me, means "overwrite" value in location k unless k == n. couple ways - depends on how assignment worded. if doesn't matter size array start start array size being n+1 (or n+somearbitraryvalue) instead of n. if have keep size @ n or n+1 depending on k==n check when k==n need setup new array size n+1 , copy values it.

hope helps without giving away.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -