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 ...
- 03-31-2007 #1
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
- 03-31-2007 #2
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
- 04-01-2007 #3
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
- 04-01-2007 #4
^^^^ 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


Reply With Quote