1
package game1;
import java.util.Scanner;

public class toothpicks {

    private int number;
    public int HowMany()
    {
        do
        {
            System.out.print("Enter the No. of ToothPicks = ");
            Scanner input =new Scanner(System.in);
            number = input.nextInt(); 
            if(number<4)
            {
                System.out.print("ToothPicks Should be greater than 3\n");

            }

        }while(number<4);

        return number;
    }
}

Where can I close the input Scanner in my program? It giving me error if I close it in the end of the Program just before return statment says input can not be resolved but if I close it in the loop then I cannot achieve what i'm trying to by using this HowMany Method? What to do ? Any help would be appreciated

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
sony
  • 375
  • 1
  • 6
  • 21

3 Answers3

2

You are creating a new instance of Scanner on each loop. You don't need to, though, so you can just do

Scanner input = new Scanner(System.in);
// do while loop goes here

And then close the Scanner just before the return statement.

eric.m
  • 1,577
  • 10
  • 20
1

You can declare your Scanner out of the loop (look that you are creating a new instance of Scanner each time the loop make an iteration)

package game1;
import java.util.Scanner;

public class toothpicks {

 private int number;
    public int HowMany()
    {
        Scanner input =new Scanner(System.in);

        do
        {
            System.out.print("Enter the No. of ToothPicks = ");

            number = input.nextInt(); 
            if(number<4)
            {
                System.out.print("ToothPicks Should be greater than 3\n");

            }

        }while(number<4);

        input.close();

        return number;
    }
}

And then close it before the return statement.

I expect it will be helpful for you!

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
1

Define and initialise input and number before the do loop, and close it immediately after the do loop.

Dodo
  • 323
  • 1
  • 8