Discuss / Java / 交作业

交作业

Topic source

import java.util.Scanner;

import java.util.Random;

public class Main {

public static void main(String[] args) throws Exception {

Scanner sc =new Scanner(System.in);

for(;;) {

System.out.println("请出拳");

String s = sc.nextLine();

System.out.println(s);

if(s.equals("e")) {

System.out.println("exit....");

break;

}else {

var you = new JiandaoShitouBu(s);

int i = new Random().nextInt(3);

var computer = new JiandaoShitouBu(i);

switch(you.complare(computer)) {

case 0 ->{System.out.printf("你出的%s,电脑出的%s,平局\n",you,computer);}

case 1 ->{System.out.printf("你出的%s,电脑出的%s,你赢了\n",you,computer);}

case -1 ->{System.out.printf("你出的%s,电脑出的%s,你输了\n",you,computer);}

default -> {

throw new Exception();

}

}

}

}

}

}

 class JiandaoShitouBu {

enum T{

Jiandao,Shitou,Bu;

}

T t;

public JiandaoShitouBu(String s) {

switch(s) {

case "j" ->{this.t=T.Jiandao;}

case "s" ->{this.t=T.Shitou;}

case "b" ->{this.t=T.Bu;}

default ->{throw new IllegalArgumentException("只允许填入j,s,b");  }

}

}

public JiandaoShitouBu(int s) {

switch(s) {

case 0 ->{this.t=T.Jiandao;}

case 1 ->{this.t=T.Shitou;}

case 2 ->{this.t=T.Bu;}

default ->{throw new IllegalArgumentException("只允许填入0,1,2");  }

}

}

@Override

public String toString() {

switch(this.t) {

case Jiandao -> {return "剪刀";}

case Shitou -> {return "石头";}

case Bu -> {return "布";}

default ->{return this.t.toString();}

}

}

public int complare(JiandaoShitouBu y) {

switch(this.t) {

case Jiandao -> {

switch(y.t) {

case Shitou->{

return -1;

}

case Bu ->{

return 1;

}

default -> {

return 0;

}

}

}

case Shitou -> {

switch(y.t) {

case Jiandao->{

return 1;

}

case Bu ->{

return -1;

}

default -> {

return 0;

}

}

}

case Bu -> {

switch(y.t) {

case Shitou->{

return 1;

}

case Jiandao ->{

return -1;

}

default -> {

return 0;

}

}

}

default -> throw new IllegalArgumentException("Unexpected value: " + this.t);

}

}

}


  • 1

Reply