我已经编写了程序并运行了它,但我不知道如何防止println语句在我用无效数字运行时出现。它基本上是一个你输入月份和时间的程序。一天(数值),输出将是季节。这是代码:
Thread.sleep()
答案 0 :(得分:2)
写:
file.open( games );
if( file.is_open() )
{
for( int x = 0; x < BOARD_SIZE; x++)
{
for (int y = 0; y < BOARD_SIZE; y++)
{
char point = 'C';
if( !file.get( point ) )
std::cout << "Error reading " << x << "," << y << std::endl;
chessBoards[x][y] = point;
}
}
}
然后在最后一个if之前检查:
String season = null;
答案 1 :(得分:1)
一种方法可能是:
boolean invalid = false;
if (month <= 3)
{
season = winter;
}
else if (month <= 6)
{
season = spring;
}
else if (month <= 9)
{
season = summer;
}
else if (month <= 12)
{
season = fall;
} else {
invalid = true;
}
if(invalid){
System.out.println("The value is invalid.");
} else {
System.out.println(season);
}
您唯一要做的就是记住日期是否无效。因此,您需要一个布尔标志invalid
。
答案 2 :(得分:1)
最简单的方法是测试如下。否则,您将设置一个真正的假标志并在最后测试它以确定要打印的内容。请注意,系统默认设置为无效,因此错误打印输出将是 季节无效
另一种方法是使用适当的情况进行switch语句,并将默认设置为make season无效。这样就不需要做所有的elseif语句了。但是,我正在展示if elseif,以保持原来的问题。
System.out.println("Enter a month: ");
month = in.nextInt();
System.out.println("Enter a day: ");
day = in.nextInt();
String winter = "winter";
String spring = "spring";
String summer = "summer";
String fall = "fall";
String invalid = "invalid";
String season = invalid; // Set the default to invalid
System.out.println("Month="+ month +" Day= "+day);
if (month > 12 || month < 1)
{
season = invalid;
}
elseif (month > 9)
{
season = fall;
}
if (month > 6)
{
season = summer;
}
else if (month > 3)
{
season = spring;
}
else
{
season = winter;
}
System.out.println("season is ", season);
答案 3 :(得分:0)
将season
设置为null
,并在打印前检查null
。删除最后一个else
if (season != null) {
System.out.println(season);
} else {
System.out.println("The value is invalid.");
}
答案 4 :(得分:0)
我建议封装if语句。您无需使用null
。并且您只能获得有效季节的输出。
if (month > 12 || month < 1)
{
season = invalid;
} else {
if (month > 9)
{
season = fall;
}
else if (month > 6)
{
season = summer;
}
else if (month > 3)
{
season = spring;
}
else
{
season = winter;
}
System.out.println("season is ", season);
}