今天学了switch语句,以及break、continue、return区别。break循环或switch中使用中断后面的语句,continue循环中使用跳出此次循环而继续下次,return则会跳出整个方法。下面是优化后的猜拳代码(检讨昨天的代码自己真想复杂了)
import java.util.Scanner; public class test { public static void main(String[] args) { ; int inp=0; //定义输入的数值 String sRnd=""; //随机数表示出拳 int numWin=0; //胜场 int numLost=0; //负场 while (true) { boolean flag=true; //立个flag备用 int rnd = (int) (1 + Math.random() * 3); System.out.print("请输入“剪刀”、“石头”或“布”,输入“退出”结束游戏:"); Scanner input = new Scanner(System.in); String sInp = input.next(); switch (sInp) { //输入文字转数字 case "剪刀": inp = 1; break; case "石头": inp = 2; break; case "布": inp = 3; break; case "退出": System.out.println("您已退出!\n "); return; default: System.out.println("输入有误! \n"); //输入错误时flag为假 flag=false; break; } switch (rnd) { //随机数转换成出拳 case 1: sRnd = "剪刀"; break; case 2: sRnd = "石头"; break; case 3: sRnd = "布"; break; default: break; } if (flag==false){ //前面立的flag为假了,跳过这次循环 continue; } else if (inp == rnd) { System.out.println("平局! ta也是"+sRnd+" 胜"+numWin+"负"+numLost+"\n"); } else if (inp == 1 && rnd == 3 || inp == 2 && rnd == 1 || inp == 3 && rnd == 2) { //列出所有胜局情况 System.out.println("你赢了!ta是"+sRnd+" 胜"+ ++numWin+"负"+numLost+"\n"); } else { System.out.println("电脑胜!ta是 "+sRnd+" 胜"+numWin+"负"+ ++numLost+"\n"); //其他都是负局情况 } } } }