PopTart_Flavored
PopTart_Flavored

Reputation: 1

java How to use 1 scanner in a loop

I am trying to learn java and am converting code for a Rock Paper Scissors game from python to java. The one issue I have right now is getting Scanner to get a new answer each round in a loop. here is what I have right now.

import java.util.Scanner;

public class PlayerInput {

public static String playerChoice(){
    String Pchoice;
    Pchoice = "n";
    Scanner pChoice = new Scanner(System.in);
    while(pChoice.hasNextLine()){
    Pchoice = pChoice.nextLine();
    Pchoice = capitalizeFirstLetter(Pchoice);
    if(Pchoice.equals("R")||Pchoice.equals("Rock")||Pchoice.equals("P")||Pchoice.equals("Paper")||Pchoice.equals("S")||Pchoice.equals("Scissors")){
    break; }}
    pChoice.close();
        if(Pchoice.equals("R")||Pchoice.equals("Rock")){
            Pchoice = "Rock";
        }else if (Pchoice.equals("P")||Pchoice.equals("Paper")){
            Pchoice = "Paper";
        }else if (Pchoice.equals("S")||Pchoice.equals("Scissors")){
            Pchoice = "Scissors";
        }else {
            System.out.println("Please try again and enter Rock (R), Paper(P), or Scissors(S)");
            playerChoice();
        }
    return Pchoice;
}


public class Start {

public static void main(String[] args) {

    PlayerInput magic = new PlayerInput();

    String name = magic.nameGetter();
    System.out.println("Hello " + name);

    for(int x = 0; x <=5; x++){
    String Pchoice = PlayerInput.playerChoice();
    System.out.println("You chose: " + Pchoice);
    }
    PlayerInput.playAgain();
}
}

I do have the other functions/methods called through these two I just didn't include them here.

Upvotes: 0

Views: 41

Answers (1)

hereForLearing
hereForLearing

Reputation: 1288

Don't close the Scanner in your playerChoice method, it would be better if you open it and close it in your main method

Upvotes: 1

Related Questions