-5

I want to write a code that will allow the user to pick how many scanners he wants to use. First I created a simple scanner and assigned an int to it

    Scanner scanner = new Scanner(System.in);
    int input = scanner.nextInt();

now the user will enter ANY integer (ex. 7). Then I want the program to create an array of scanners that will then allow a number of lines of input (in this case 7). Any help is appreciated!

6
  • Can i get an explanation on the down vote please, for future improvements.
    – daniel p
    Feb 10, 2015 at 23:53
  • 1
    It was not me, but why do you need multiple scanners?
    – msfoster
    Feb 10, 2015 at 23:54
  • Just use a loop and a List. Not sure why you would want to do this, though.
    – TNT
    Feb 10, 2015 at 23:55
  • Not the downvoter, but I'm certain that's not what you want. You're probably looking to create a number of some data object instead and store it in an array or list. Feb 10, 2015 at 23:55
  • 1
    @danielp Creating multiple scanners will not do what you want because of how they interact with the input stream. You need to learn the basic loops, which you would have to have to use your multiple scanners anyway. Feb 11, 2015 at 0:37

1 Answer 1

0

To create a specific number of objects and store them somewhere you can easily use arrays:

Scanner[] scanners = new Scanner[num_of_scanners];

At this point you will have an array of null scanner objects. To declare them properly you have to use a loop like this:

for (int i = 0; i < scanners.length; i++)
{
    scanners[i] = new Scanner(System.in);
}

Now you succesfully initialized all the scanners. To get your scanner at certain index see the example below:

Scanner first_scanner = scanners[0];

More on arrays here.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.