java 猜数字游戏,第一个java实验,求指教。。。。
//感觉你这个全部集中在一个方法中,显得太乱了。
//分到几个方法中,更为清晰。
package?firstProject;
import?java.util.Random;
import?java.util.Scanner;
public?class?GuessGame?{
public?static?void?main(String[]?args)?{
GuessGame?game?=?new?GuessGame();
game.start();
}
private?Scanner?scanner?=?new?Scanner(System.in);
private?int?gameCount;
private?int?winCount;
private?int?failCount;
private?void?start()?{
while?(true)?{
if?(playGame())?{
gameCount++;
winCount++;
}?else?{
gameCount++;
failCount++;
}
if?(!restart())?{
break;
}
}
System.out.println("您一***进行了"?+?gameCount?+?"次游戏");
System.out.println("成功了"?+?winCount?+?"次");
System.out.println("失败了"?+?failCount?+?"次");
System.out.println("游戏结束");
}
private?boolean?playGame()?{
System.out.println("游戏开始");
int?target?=?new?Random().nextInt(11);
for?(int?i?=?0;?i?<?3;?i++)?{
int?userInput?=?userInput();
if?(target?==?userInput)?{
System.out.println("恭喜你猜对了");
return?true;
}
if?(userInput?>?target)?{
System.out.println("您输入的太大了");
}?else?{
System.out.println("您输入的太小了");
}
}
System.out.println("你失败了");
return?false;
}
private?int?userInput()?{
System.out.println("这是一个0到10的整数:");
System.out.println("请输入您猜的数字:");
try?{
return?Integer.parseInt(scanner.nextLine());
}?catch?(Exception?e)?{
return?userInput();
}
}
private?boolean?restart()?{
System.out.println("您还要继续吗?(y/n)");
return?scanner.nextLine().equalsIgnoreCase("y");
}
}