Find the answer to your Linux question:
Results 1 to 4 of 4
public static void main(String args[]) { int n = keyboard.nextInt(); int[] input = new int[n]; for(int i=0; i < (input.length - 1); i++) input[i] = keyboard.nextInt(); } What this simple ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux User tech_man's Avatar
    Join Date
    Jan 2007
    Location
    USA
    Posts
    385

    Java Scanner Issue


    public static void main(String args[])
    {
    int n = keyboard.nextInt();
    int[] input = new int[n];
    for(int i=0; i < (input.length - 1); i++)
    input[i] = keyboard.nextInt();
    }

    What this simple program intends to do is ask the user how many ints he will be entering. Once he enters the number, an array of size n is created and then a loop fills the array with user input.

    The problem is that the loop is executing n-1 times instead of n times! I know some Java master will know what the problem is.
    'Tis better to be silent and be thought a fool, than to speak and remove all doubt.'
    --Abraham Lincoln

  2. #2
    Linux User tech_man's Avatar
    Join Date
    Jan 2007
    Location
    USA
    Posts
    385
    Follow up:

    Why will this not work:

    int n = keyboard.nextInt();
    BigInteger[] input = new BigInteger[n];
    for(int i=0; i < (input.length - 1); i++)
    input[i] = new BigInteger(keyboard.nextLine());


    Why will this work:

    int n = keyboard.nextInt();
    BigInteger[] input = new BigInteger[n+1];
    keyboard.nextLine();
    for(int i=0; i < (input.length - 1); i++)
    input[i] = new BigInteger(keyboard.nextLine());
    'Tis better to be silent and be thought a fool, than to speak and remove all doubt.'
    --Abraham Lincoln

  3. #3
    Linux Newbie birdman's Avatar
    Join Date
    Mar 2006
    Location
    Ireland
    Posts
    141
    Take out the -1 from the conditional test in the for loop.

    What is happening is that after the n-1 iteration (where i is equal to n-2 due to the numbering starting at 0), i is then incremented by 1 and is now equal to n-1. Your conditional statement is effectively asking the loop to continue while i is less than n-1. As i=n-1 this is no longer the case and the loop is no longer executed.

    Regards

  4. $spacer_open
    $spacer_close
  5. #4
    Linux User tech_man's Avatar
    Join Date
    Jan 2007
    Location
    USA
    Posts
    385
    ^^^^ Thanks A lot! I thought I had an = there!
    'Tis better to be silent and be thought a fool, than to speak and remove all doubt.'
    --Abraham Lincoln

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •