gpt4 book ai didi

java - 如何正确地为变量分配 boolean 值并对其进行测试?

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

我正在尝试创建一个类,使用三个整数变量来设置时间,分别表示小时、分钟和秒数,以及第四个 boolean 变量来设置 AM 或 PM。我能够使三个整数变量正常工作,但我不知道我在 boolean 变量未正确分配或测试方面做错了什么。

public class Time
{
private int hour;
private int minute;
private int second;
private boolean amPm;

public Time(int setHour, int setMinute, int setSecond, boolean setAmPm)
{
hour = setHour;
minute = setMinute;
second = setSecond;
amPm = setAmPm;
}

public String toString()
{
if (amPm == true)
{
String halfDay = "P.M.";
}
else
{
String halfDay = "A.M.";
}
return hour + ":" + minute + ":" + second + " " + halfDay + ".";
}
}

最佳答案

您不能使用 halfDay,因为它超出了范围

In computer programming, the scope of a name binding – an association of a name to an entity, such as a variable – is the region of a computer program where the binding is valid: where the name can be used to refer to the entity. Such a region is referred to as a scope block. In other parts of the program the name may refer to a different entity (it may have a different binding), or to nothing at all (it may be unbound).

在其他世界中,您在 if/else 语句中声明 halfDay,但一旦您关闭括号,它就会消失。如果您想将它用于串联,则需要通过之前声明来更改他的范围。

public class Time
{
private int hour;
private int minute;
private int second;
private boolean amPm;

public Time(int setHour, int setMinute, int setSecond, boolean setAmPm)
{
hour = setHour;
minute = setMinute;
second = setSecond;
amPm = setAmPm;
}

public String toString()
{
String halfDay;
if (amPm == true)
{
halfDay = "P.M.";
}
else
{
halfDay = "A.M.";
}
return hour + ":" + minute + ":" + second + " " + halfDay + ".";
}
}

关于java - 如何正确地为变量分配 boolean 值并对其进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49409379/

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