在Java中,可以用nextLine()读取一行文本。然后再用Intger.parseIn(),charAt(0)分别转换为Int,char型变量。
以下是一个与电脑猜拳的程序
package 与电脑猜拳游戏
import java.util.Scanner;
import java.util.Random;
public class PlayFingerGuessingGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("*********** Play Finger Guessing Game****************\n"+
" game rule:0---rock\n 1---paper\n 2---Scissors\n"+
"************Enjoy the game now.***************");
int count=0,Pwin=0,Pdefeat=0,player,computer;
String s;
do{
System.out.println("It's your turn to punch('Q'end),please:");
Scanner input = new Scanner(System.in);
s = input.nextLine();
char c = s.charAt(0);
if (c == 'Q') break;
player = Integer.parseInt(s);
Random r = new Random();
computer = r.nextInt(3);
switch (computer)
{
case 0 :
System.out.println("Computer----rock");
break;
case 1:
System.out.println("Computer----paper");
break;
case 2:
System.out.println("Computer----Scissors");
break;
default:
System.out.println("Wrong");
}
if ( player==computer)
System.out.println("result*******Draw");
else
if (player+1==computer || (computer==0 && player == 2))
{
System.out.println("result*******Computer Win");
Pdefeat++;
}
else {
System.out.println("result*******Player Win");
Pwin++;
}
count++;
}while (true);
System.out.println("**********game over*********\n"
+"*The players are as follows: *\n"+" 总局数:"+count+"\n"
+" 玩家胜局数:"+Pwin+"\n"+" 玩家败局数:"+Pdefeat+"\n"
+" 平局:"+ (count-Pwin-Pdefeat)+"\n");
}
}