Your approach is basically right, but you have a few issues going on. I'll try to run you through it:
public static void main (String args[])
{
int number;
Scanner sc = new Scanner(System.in);
int counter = Integer.parseInt(sc.nextLine()); // You get a number
System.out.println("enter a number"); // You ask to enter a number
number = sc.nextInt(); // You get another number
for(counter =1; counter <= number; counter++) { // Well...
System.out.println("Enter a number");
number = sc.nextInt();
}
}
The first thing I noticed is that you get two numbers from the user right at the beginning. You use different approaches (both should work) and only ask for a number after you already collected the first one. This should be reduced to only get one number, like this:
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
int num = sc.nextInt();
Let's take it step by step. At this point you know how many numbers you need to ask for. But what if the user entered a negative number? Let's check!
if (num < 0) {
System.out.println("You entered a negative number. Aborting.");
return;
}
The program will end at this point as the user gave a non-valid input.
But let's assume the user gave a positive number. What next? Well, you can now use the given number as the condition in your loop. This means we need an additional variable, our loop counter, to compare it to. Usually this is named i
and we start from 0
, not 1
:
for (int i = 0; i < num; ++i) { /* ... */ }
Great, that looks good. But what do we do in the loop? Well, you were basically doing it right, just that you might want to add some output so the user (you) will get some feedback. How about:
System.out.println("Enter number " + Integer.toString(i + 1));
int n = sc.nextInt();
System.out.println("You entered: " + Integer.toString(n));
That should do the trick. I haven't tested it, but you should have something left to work on anyway.
Notice how I used string concatenation to give the user a better idea of where he is in the process. Since we can't just add numbers to a string, we first have to turn it into a string with Integer.toString()
. And that's all the magic there is.
Hope this helps!