gpt4 book ai didi

java - 有没有办法为 int 设置范围?当某个 int 超出该范围时,另一个 int 递增 1

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

构建一个包含英制重量(英石、磅和盎司)的程序,我需要磅和盎司的范围(即盎司 0-15),一旦盎司 int 超过 15,则磅将增加 1 ,同样的情况也发生在磅上,因此石头增加 1。

我是 Java 的新手,所以这对我来说是新的,我不知道如何开始。

public class NewWeight {

private int stones = 0;
private int pounds = 0;
private int ounces = 0;

public NewWeight (int stones, int pounds, int ounces) {
...


假设输入 18 盎司,输出将是 1 磅 2 盎司,另一个示例是 224 盎司,因此输出最终将是 1 stone, 0磅,0 盎司

最佳答案

您不必在此处使用 3 个变量 ouncespoundsstones。这三个都代表一个量——重量。

您可以仅以盎司为单位存储重量,而不是其他:

private int weightInOunces;

然后您可以添加方法,例如 getPoundsgetStonesgetOunces,它们对 weightInOunces 进行数学计算。

例如:

public int getPounds() {
return weightInOunces % 224 / 16;
}

public int getOunces() {
return weightInOunces % 16;
}

public int getStones() {
return weightInOunces / 224;
}

Setter 可以这样实现:

public int setPounds(int pounds) {
int stones = getStones();
weightInOunces = stones * 244 + getOunces() + pounds * 16;
}

public int setOunces(int ounces) {
int pounds = getPounds();
weightInOunces = pounds * 16 + ounces;
}

public int setStones(int stones) {
weightInOunces = stones * 244 + weightInOunces % 244;
}

构造函数可以这样实现:

public Weight(int stones, int pounds, int ounces) {
weightInOunces = stones * 224 + pounds * 16 + ounces;
}

要实现输出,您还可以添加一个toString 方法,以x stones, x pounds, x ounces 格式输出重量。

关于java - 有没有办法为 int 设置范围?当某个 int 超出该范围时,另一个 int 递增 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55936250/

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