So I'm really new to Java, and I'm making a program for school. I'm having an issue using the scanner properly.
public int[] userShoot(int shotType)
{
int[] returnThis = {0,0};
int hitFlag = 0, shotProb;
int flag = 1;
if(shotType != 0)
{
while(flag == 1)
{
System.out.println("Pick a shot");
System.out.println("1: Field Goal (Normal)");
System.out.println("2: Three Pointer (Hard)");
System.out.println("3: Backwards Field Goal (Hard)");
System.out.println("4: Backwards Three Pointer (Very Hard)");
System.out.println("5: Trickshot (Completely Random");
Scanner sc = new Scanner(System.in);
shotType = sc.nextInt();
sc.close();
if(shotType >= 1 && shotType <= 5)
{
flag = 0;
}
else
{
flag = 1;
System.out.println("Invalid Response.");
}
}
}
switch(shotType)
....
returnThis[0] = shotType;
returnThis[1] = hitFlag;
return returnThis;
}
With this version of my code, I got a NoSuchElement exception after the first run of the while loop. So I searched for fixes to this exception, and most answers told me to use hasNextInt().
So I changed my code to have
Scanner sc = new Scanner(System.in);
if(sc.HasNextInt())
shotType = sc.nextInt();
else
shotType = 0;
Now of course the obvious issue here is that if I make shotType = 0, I get an invalid response. And then it just loops, unable to actually break out of the while loop. So my question is: how do I properly take multiple inputs in Java through a while loop, such as in this block of code? I don't know how to fix the input getting exhausted through each loop of the code. Do I have to close the scanner outside of the loop?
EDIT: I tried closing outside of the loop like this:
Scanner sc = new Scanner(System.in);
while(flag == 1)
{....}
sc.close();
But that didn't fix, it still gave the NoSuchElement exception
EDIT2:
Combining both fixes worked, but didn't give me the behavior that I need. Code as follows:
Scanner sc = new Scanner(System.in);
while(flag == 1)
{
...
if(sc.hasNextInt())
shotType = sc.nextInt();
...
}
sc.close();
The issue now is that it only keeps the first input, and doesn't allow the user to input each time the while loop, loops.
EDIT3:
Opening and closing my scanner outside of my userShoot method worked.
However, I also had to change the prototype and calls of the method.
IE userShoot(int shotType, Scanner sc);
as the prototype, and when calling it: userShoot(shotType, sc);
Thanks everyone for the help!!