因此,对于我的类,我们只是在学习如何编写方法。我正在写一个掷2个骰子的游戏,如果它们是相同的,你就赢了,如果它们不同,你就输了。我应该循环它,直到用户决定退出。然后我将打印出玩过的回合数和赢/输。它完美地运行了一次,但我不确定如何循环,直到用户决定退出。我不能循环整个方法,所以我不确定该怎么做。我在想,布尔值可能会以某种方式在main方法中工作,但不确定。这是我到目前为止所做的。谢谢。
import java.util.Scanner;
public class Project07 {
public static void main(String[] args)
{
welcome();
int r1 = rolldie();
int r2 = rolldie();
printdice(r1,r2);
boolean b;
b = ispair(r1,r2);
report(b);
}
public static void welcome()
{
System.out.println("Welcome to Computer Dice");
System.out.println("You will first roll your dice");
System.out.println("Next the outcome of your roll will be determined");
System.out.println("any pair and you Win");
System.out.println("anything else and you Lose");
System.out.println();
System.out.println();
String y;
Scanner stdIn= new Scanner(System.in);
do{
System.out.println("Press enter to roll");
y=stdIn.nextLine();
} while(!y.equals(""));
}
public static int rolldie()
{
int die;
die = (int)(Math.random()*6+1);
return die;
}
public static void printdice(int r1, int r2)
{
System.out.println("Your Roll: "+(r1) + (" ") + (r2) );
System.out.println();
}
public static boolean ispair(int r1,int r2)
{
boolean b;
if (r1==r2)
{
b=true;
}
else
{
b=false;
}
return b;
}
public static void report(boolean b)
{
Scanner stdIn= new Scanner(System.in);
String one;
int gamesplayed=0;
int sumwins=0;
int sumlosses= 0;
if(b==true)
{
System.out.println("You Win!");
System.out.println();
sumwins=sumwins+1;
}
else
{
System.out.println("You Lose!");
System.out.println();
sumlosses=sumlosses+1;
}
gamesplayed=gamesplayed+1;
do{
System.out.println("Do you want to play again (y/n): ");
one= stdIn.next();
} while(!one.equalsIgnoreCase("y") && !one.equalsIgnoreCase("n"));
if (one.equalsIgnoreCase("y"))
{
}
else
{
System.out.println("You Played "+(gamesplayed)+ (" rounds"));
System.out.println("You won "+(sumwins)+ (" rounds"));
System.out.println("You lost "+(sumlosses)+ (" rounds"));
}
}
}发布于 2013-11-19 10:27:36
您可以尝试如下所示:
String y;
Scanner stdIn= new Scanner(System.in);
do{
System.out.println("Press enter to roll");
y=stdIn.nextLine().charAt(0);
} while(y.equals("y"));然后,如果用户输入了除以y开头的单词之外的任何内容,它将终止循环。
https://stackoverflow.com/questions/20061698
复制相似问题