gpt4 book ai didi

java - 在Java中如何将整数方法转换为字符串方法?

转载 作者:行者123 更新时间:2023-12-01 20:54:43 25 4
gpt4 key购买 nike

我正在尝试创建一个骰子程序,我需要输出为“一”、“二”、“三”等字符串。它当前打印的输出为 0,但这是因为我的 OutputDice方法不正确。当我取出它时,它将参数作为整数传递,但我需要它们作为字符串。我该怎么做?

我的代码如下:

import java.util.Random;

public class Dice {

private int Value;

public void setValue(int diceValue)
{
Value = diceValue;
}
public int getValue()
{
return Value;
}
public void roll()
{
Random rand = new Random();
Value = rand.nextInt(6) + 1;
}
public void OutputDice()
{
switch (Value)
{
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
case 4:
System.out.println("Four");
case 5:
System.out.println("Five");
case 6:
System.out.println("Six");
}
}
}

public class DiceRoll {

public static void main(String[]args) {

Dice firstDie = new Dice();
Dice secondDie = new Dice();

firstDie.OutputDice();
secondDie.OutputDice();

System.out.println("Dice 1: "+ firstDie.getValue());
System.out.println("Dice 2: "+ secondDie.getValue());
}
}

最佳答案

你也永远不会给你的骰子赋值。在显示值之前,您需要调用 roll() 方法。另外,使用 switch case 语句,您需要在 case 之后包含中断,如下所示

public void OutputDice()
{
switch (Value)
{
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
case 5:
System.out.println("Five");
break;
case 6:
System.out.println("Six");
break;
}
}

关于java - 在Java中如何将整数方法转换为字符串方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546008/

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