Discuss / Java / switch

switch

Topic source
package com.itranswarp.learnjava;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
		System.out.println("please choice:");
		System.out.println(" 1: Rock");
		System.out.println(" 2: Scissors");
		System.out.println(" 3: Paper");
		String[] str = {"", "Rock", "Scissors", "Paper"};
		Scanner scan = new Scanner(System.in);
		int choice = scan.nextInt();
		if(choice > 3 || choice <= 0) {
			System.out.println("wrong number!");
			scan.close();
			return;
		}
		int random = 1 + (int)(Math.random() * 3);
		System.out.printf("you shows \"%s\", computer shows \"%s\",", str[choice], str[random]);
		switch(choice -random) {
			case -1:
			case 2:
				System.out.println("you win!!");
				break;
			case 0:
				System.out.println("draw!!");
				break;
			case 1:
			case -2:
				System.out.println("you lose!!");
				break;
			default:
				break;
		}
		scan.close();
	}
}

random没有限定范围,数组越界了,你那个Math.random() * 3,中间的*应该是%吧.


  • 1

Reply