首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当按回车键时,程序将无法继续。如何修复此错误?

当按回车键时,程序将无法继续。如何修复此错误?
EN

Stack Overflow用户
提问于 2019-05-09 03:27:56
回答 1查看 42关注 0票数 1

我正在为我的java课程做一个石头剪刀的家庭作业。我已经完成了这个程序,我成功地编译了它。我运行了这个文件,它看起来像是在工作。它给了我菜单,我选择了一个变量,例如R,当我按enter时,它不会做任何事情,只会转到下一行。我再次按回车键,它会给我一个索引越界错误,我认为这是因为第二次它没有变量可用。我如何让程序向前发展?该程序应该播放五次,然后返回一个获胜者。提前感谢。This image is what I get when I run the program and press enter twice

package Rock;
import java.util.Scanner;




public class RPSG {




public static void main(String[] args) {

    String[] computerHandArray = {"R","P","S"};
    String computerHand ="", thisWinner="", theFinalWinner="";
    int index=0;
    int timesIWon=0;
    int timesComputerWon=0;
    Scanner in = new Scanner(System.in);
    System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\nEnter Your Hand (R, P, or S): ");
    for (int i=0; i<5; i++) {
        String myHandString = in.nextLine();
        String myHand = myHandString.substring(0,1);
        myHand = myHand.toUpperCase();
        index = (int)(Math.random() * 10) % 3;
        computerHand = computerHandArray[index];
        thisWinner = theWinnerofOneGame(myHand, computerHand);

        if(thisWinner.equals("ME")){
            timesIWon++;
        }
            else if(thisWinner.equals("COMPUTER")) {
                timesComputerWon++;
        }
    }

        if(timesIWon == timesComputerWon)
        theFinalWinner = "TIE";
    else if(timesIWon > timesComputerWon)
            theFinalWinner = "ME";
    else if(timesComputerWon > timesIWon)
        theFinalWinner = "COMPUTER";
    System.out.println("I won :" + timesIWon);
    System.out.println("I won :" + timesComputerWon);
    System.out.println("The Final Winner after 5 games is:" +theFinalWinner);
    }
private static String theWinnerofOneGame(String myHand, String computerHand){
    String theWinner = "Tie";
    if(myHand.equals(computerHand)) {
        theWinner = "Tie"; 
}
    else if(myHand.equals("R")) {
        if (computerHand.equals("P")) {
            theWinner = "COMPUTER";
        }
    }

    else if(computerHand.equals("S")) {
        theWinner = "ME";
    }

else if(myHand.equals("P")) {
    if (computerHand.equals("R")) {
        theWinner = "ME";
    }
    else if(computerHand.equals("S")) {
        theWinner = "COMPUTER";
        }
    }
else if(myHand.equals("S")) {
    if (computerHand.equals("R")) {
        theWinner = "COMPUTER";

    }

    else if(computerHand.equals("P")) {
        theWinner = "ME";
    }
}
    return theWinner;
    }

}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56047780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档