好吧我有我的搖滾,紙,剪刀遊戲工作。除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