0

I'm practicing for my first java exam by doing questions/programs from the book. One question seems to be too overwhelming for me:

Create a code that will prompt for a number from the user. Then the system will prompt for a new number as many times as the first number. Input can has positive AND negative numbers, like:

3
-20
4
5

public static void main (String args[])
{
    int number;

    Scanner sc = new Scanner(System.in);
    int counter = Integer.parseInt(sc.nextLine());  
    System.out.println("enter a number");
    number = sc.nextInt();

    for (counter = 1; counter <= number; counter++)   //doesn't work with negatives
    {
        System.out.println("Enter a number");    //how to repeat times first input
        number = sc.nextInt();
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
buliukko
  • 41
  • 6
  • 2
    don't reuse the same variable for all inputs - if I understood correctly you're supposed to store the following inputs in an array (or `List`) and output them at the end – UnholySheep Mar 08 '17 at 15:31
  • 1
    I think your approach is right. However, could it be that the positive and negative input only holds true for everything *but* the first number? It simply doesn't make sense for the first one. "I want to put in -5 more numbers"? Alternatively, just check if the `counter` is negative and gracefully abort with a message if so. – domsson Mar 08 '17 at 15:32
  • 1
    What should happen when it's a negative number? Clearly the system can't prompt you for -20 more inputs... do you want something like "Math.max(0, counter)" so that negatives are treated as zero? – Matt Mar 08 '17 at 15:33
  • Ha, the @UnholySheep is right. And now I see quite some other errors. – domsson Mar 08 '17 at 15:33
  • mmmh I can't understand your question. Do you want to ask only once for a number (say 3) and then ask for 3 new numbers? – LppEdd Mar 08 '17 at 15:40
  • Yes, forgot to add that I have to store the numbers. I haven't learned about arrays yet, so I think in this case just a list. – buliukko Mar 08 '17 at 16:07
  • buliukko, this question has been answered/solved quite a while ago - please remember to mark one of the provided answers as *accepted* (tick mark on the left) so the question will be marked *solved*. – domsson Jul 04 '17 at 10:53

3 Answers3

0

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!

domsson
  • 4,553
  • 2
  • 22
  • 40
  • Thanks @UnholySheep, forgot about it. Added it to the answer. – domsson Mar 08 '17 at 15:44
  • Two more things: first, you could handle negative numbers in a way that do not end the program. One example is given in @LppEdd's answer, but there are other possibilities. Second, what if the user entered a really huge number in the beginning? He would have to put in numbers for a long time. Maybe add a way for the user to *break out* of the loop and end the program prematurely. Can you come up with a solution? – domsson Mar 08 '17 at 15:51
  • And one more to think about: it would be a nicer program if we didn't just spit the entered numbers right back at the user but instead save them and do something with them after the loop. For example, calculate the sum and print that? If you want to tackle that, you would need to read about arrays and/or collections. – domsson Mar 08 '17 at 15:54
  • Glad I could be of help, @buliukko! Remember to choose one of the answers as accepted/best answer, as is common on Stack Overflow. :) – domsson Mar 08 '17 at 18:48
0

Is this what you are looking for?

public class Test
{
   private static final Scanner SCANNER = new Scanner(System.in);

   public static void main(final String args[]) {
      System.out.print("Enter a number: ");
      int number = SCANNER.nextInt();

      if (number < 0) {
         number *= -1;
      }

      for (int i = 0; i < number; i++) {
         System.out.print("Enter a number: ");
         SCANNER.nextInt();
      }
   }
}
LppEdd
  • 20,274
  • 11
  • 84
  • 139
0

You don't need the user to enter a counter

       int counter = Integer.parseInt(sc.nextLine());  

what you did here was to prompt the user for a counter and you even converted it from a String to an int .Just delete it then initialize it correctly in your for-loop.By adding int before counter.

from for(counter =1; counter <= number; counter++) to for(int counter =1; counter <= number; counter++)

And you cant make number = sc.nextInt();inside the loop since number is the limit of your counter and should not change so assign another int variable to receive values from user inside the loop and don't call it number.

And your code is correct.

If you want to insert the values in an array List just add an array variable then insert values in it through the loop then print it.

Here is its full code :-

public static void main(String[] args) {

int number;

Scanner sc = new Scanner (System.in);

System.out.println("enter a number");
number = sc.nextInt();
int [] t = new int [number]; // initializing an array t of type int having a length of [number] Which is the maximum amount of values that can be stored inside the array.

for(int counter =1; counter <= number; counter++)   
{
System.out.println("Enter a number");    
int value = sc.nextInt();//stores each user value in numbers overwriting any previous value.
t[counter-1]=value;//saves the value the user entered in the array named t at the very start of the array which is at 0 
}
System.out.println("Your Array List");
for(int i =0; i<number;i++)   
{
System.out.println(t[i]);  //prints the array values from 0 till number-1 
}

}
Omar Boshra
  • 447
  • 7
  • 21
  • thank you so much for your help! I haven't learned about arrays yet... how would I save the inputs to the output? Now the system is just showing the inputs that he is entering. What if I would like to show him the numbers, that he inputs, that are even and odd ? – buliukko Mar 08 '17 at 17:07
  • @buliukko To distinguish between even and odd numbers, use the [modulo operator](http://stackoverflow.com/questions/90238/whats-the-syntax-for-mod-in-java) `%` – domsson Mar 08 '17 at 18:53
  • Add the condition `if(t[i]%2==1)` before the `System.out.print (t[i])` in the second for-loop then add another for-loop but instead add the condition `if(t[i]%2==0)` and after it the `System.out.print (t[i])`.The output console will print all the even then the odd numbers . The `%` basically gets the remainder of 2 numbers. – Omar Boshra Mar 09 '17 at 02:14
  • buliukko, if this answer was helpful, consider giving it an upvote as is common on Stack Overflow. – domsson Jul 04 '17 at 10:54