Reputation: 395
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
Upvotes: 1
Views: 799
Reputation: 313
Define and initialise input
and number
before the do
loop, and close it immediately after the do
loop.
Upvotes: 1
Reputation: 13199
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!
Upvotes: 1
Reputation: 1612
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.
Upvotes: 2