好吧我有我的摇滚,纸,剪刀游戏工作。除Q之外的所有人都退出了作品。由于我的扫描仪只采用整数,我怎样才能将“Q”字符串传递给它。我会假设我只是在while循环中添加一个简单的if(string.equals("Q") {break;}
,我很乐意去。让我知道你的想法。如何解析字符串作为整数
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
/**
* (Insert a brief description that describes the purpose of this method)
*
* @param args
*/
public static void main(String[] args)
{
int compint;
String usermove = "";
String compmove = "";
String winner = "";
int count = 0;
int input=0;
Scanner in = new Scanner(System.in);
Random gen = new Random();
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input=in.nextInt();
while (count < 3)
{
compint = gen.nextInt(3) + 1;
if (input == 1)
{
usermove = "Rock";
}
else if (input == 2)
{
usermove = "Paper";
}
else if (input == 3)
{
usermove = "Scissors";
}
if (compint == 1)
{
compmove = "Rock";
}
else if (compint == 2)
{
compmove = "Paper";
}
else if (compint == 3)
{
compmove = "Scissors";
}
if (compint == input)
{
winner = "TIE";
}
else if (compint == 1 && input == 3)
{
winner = "COMPUTER";
}
else if (compint == 2 && input == 1)
{
winner = "COMPUTER";
}
else if (compint == 3 && input == 2)
{
winner = "COMPUTER";
}
else
{
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println();
count++;
System.out.print("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
}
}
}
使用'input = in.next()'(将输入改为'String'),检查input.equalsIgnoreCase(“Q”)是否与'int'一致,的Integer.parseInt(输入)'。这会抛出一个'NumberFormatException',你应该捕获并提醒用户只输入有效的值 – MadProgrammer 2013-02-10 05:32:12