gpt4 book ai didi

java - 分数计算器

转载 作者:行者123 更新时间:2023-12-02 07:06:42 27 4
gpt4 key购买 nike

好吧,我对 java 很陌生。
我正在为一个我长期搁置的项目设计一个分数计算器。不过,据我所知,我想知道如何做到这一点。

程序应该要求每个玩家掷骰子,并将其添加到之前的骰子中。
我假设 while 循环可以完成此操作,但每次它经过循环时,都会将变量重置为当前滚动。因此,我无法获得总计...

下面是一些代码:

    static int players;
static String p1;
static String p2;
static String p3;
static String p4;
static int maxScore;
static int roll1;
static int roll2;
static int roll3;
static int roll4;
static int total1;
static int total2;
static int total3;
static int total4;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of players: ");
players=keyboard.nextInt();
System.out.print("Enter Maximum Score: ");
maxScore=keyboard.nextInt();
if(players==2){ //will add more ifs when i get the code right
System.out.println("Please enter players names.");
System.out.print("Player 1: ");
p1=keyboard.next();
System.out.print("Player 2: ");
p2=keyboard.next();
System.out.println(p1 + "\t \t " + p2 + "\n"
+ "_______ \t _______ \n" ); //displays scorecard look with players names

{


while (total1 < maxScore && total2<maxScore) {
//scorecard quits when maxScore is reached by either player
int roll;
total1=(roll+roll1);

System.out.print("");
roll=keyboard.nextInt(); //asks for current roll

System.out.print("\n"+"_____"+"\n");
System.out.print(roll+"+"+"\n"+roll1+"\n"+"_____"+"\n"+(roll+roll1)+"\n");
/*i want this to display total score + last roll and then
*total it again on the next line*/
roll1=roll;
}

最佳答案

关于 Java 编程进度的一些提示:

  1. 变量roll没有任何作用。 roll1 等将存储每个玩家的最后一卷。

  2. 如果可能的话,初始化您的变量。应避免依赖默认值,因为它可能会给您带来学习过程中的问题(NullPointerException 有时会拜访您)。

  3. 在循环中,您有 total1=(roll+roll1);。这是错误的。当程序到达此点时,您的变量 total1rollroll1 尚未初始化。由于它们是整数,因此它们(默默地)初始化为 0,因此此时 total1 生成 0,这并没有多大作用。之后,您可以继续取回卷筒。尝试相反的方法,先滚动,然后相加。

  4. 您提到您是 Java 新手,但是,在将来的某个时候,您可能会考虑使用数组实现相同的程序。您会发现它可以节省您现在编写的大量重复代码。

总结并转化为代码指南(适用于 2 名玩家):

public class MyScoreCalculator {
static String p1 = "";
static String p2 = "";
static int maxScore = 0;
static int roll1 = 0;
static int roll2 = 0;
static int total1 = 0;
static int total2 = 0;

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Dialogue to get data...
// Display scorecard look with players names

while (total1 < maxScore && total2 < maxScore) {
//scorecard quits when maxScore is reached by either player
roll1 = keyboard.nextInt(); // ask for current roll

System.out.println(total1 + "+");
System.out.println(roll1);
System.out.println("_____");
System.out.println(roll1 + total1);

total1 = total1 + roll1;

// Do the same for next player.
}
}
}

关于java - 分数计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024765/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com