gpt4 book ai didi

java - 比较java中的int

转载 作者:行者123 更新时间:2023-11-29 04:33:51 24 4
gpt4 key购买 nike

我有这个脚本可以在 Java 中模拟 2 个掷骰子。这是完成两次,一次由用户完成,一次由计算机完成(都是自动完成的)。该程序输出卷并将它们相加。但是,我无法获得 if/else 语句来比较掷骰并确定赢家/或领带。到目前为止,我有:

import java.util.Scanner;
import java.util.Random;
import java.text.DecimalFormat;
/*
Program to simulate die roll
*/
public class Dice
{
Scanner scan = new Scanner (System.in);
Random generator= new Random();
int roll1;
int roll2;
int roll3;
int roll4;
int addroll1;
int addroll2;

public void userdieroll() // Simulates users role
{
roll1 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("Your first roll is "+roll1+"");// Says users first role
roll2 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("Your second roll is "+roll2+"");// Says users second roll
addroll1= roll1 +roll2;// Sums users roles
System.out.println("The sum of your two roles is "+addroll1+" \n");
}
public void compdieroll()// Simulates computers role
{
roll3 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("The computers first role is "+roll3+""); // Says computers first role
roll4 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("The computers second role is "+roll4+""); // Says computers second role
addroll2= roll3 +roll4;// Sums computers roles
System.out.println("The sum of the computers roles is "+addroll2+"");
}
public void findwinner()
{
if (addroll1 == addroll2)
{
System.out.println("Its a tie!");
}
else
{
if (addroll1 > addroll2)
{
System.out.println("You Won!");
}

else
{
System.out.println("You lost!");
}

}
}
public static void main(String[] args)
{
Dice userroll = new Dice();
userroll.userdieroll();
Dice comproll = new Dice();
comproll.compdieroll();
Dice looper = new Dice();
looper.findwinner();

}

}

最佳答案

每次调用方法时,您都会创建一个新的 Dice 对象。执行此操作时,您不会将 addroll1addroll2 存储在同一对象中,因此 .findwinner() 不会存储是很自然的在您的第三个对象中没有按预期工作,您没有在 addroll1addroll2 中存储任何值。要解决此问题,请对所有三种方法使用相同的 Dice 对象,如下所示:

Dice tester = new Dice();
tester.userdieroll();
tester.compdieroll();
tester.findwinner();

关于java - 比较java中的int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42611189/

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