想知道是否有人可以帮助我将“If else声明”更改为“切换” 那么伪代码就是。 请帮忙。
IF month is 1,2, or 3, season = "Winter
Else if month is 4, 5, or 6, season = "Spring"
Else if month is 7,8, 9, season = "Summer"
Else if month is 10,11, or 12, season = "Fall"
If season is "Winter", season = "Spring"
Else if season is "Spring", season = "Summer"
Else if season is "Summer", season = "Fall"
Else season = "Winter"
2.我的代码是
import java.util.Scanner;
public class mylab
{
public static void main(String[] args)
{ Scanner in = new Scanner(System.in);
int month;
int day;
String season= "seasons";
System.out.print("type a two digit month");
System.out.print(" and day");
month = in.nextInt();
day = in.nextInt();
String fall = " fall";
String winter = " winter ";
String summer = " summer";
String spring = " spring";
System.out.print(" Month="+ month +" Day= "+day);
if( month <= 3)
{ System.out.println(" Winter");
season= winter; }
else if ( month <=6)
{ System.out.println(" Spring ");
season=spring; }
else if ( month<= 9)
{ System.out.println(" Summer ");
season= spring; }
else if ( month<=12)
{ System.out.println(" Fall");
season= fall; }
3.我只需要将第1部分更改为switch语句。 这就是我到目前为止所拥有的
switch( month )
{ case 1: season= " winter";if ( month <= 3) ;break;
case 2: season= " spring"; if ( month <= 6) ;break;
case 3: season = " summer"; if (month <= 9); break;
case 4: season= " fall"; if (month <= 12); break ;
}
,但它不起作用。
答案 0 :(得分:2)
如果月份为1,2或3,则赛季=“冬季
会变成......
String season = "";
switch (month) {
case 1:
case 2:
case 3:
season = "Winter";
break;
case ...: // etc...
}
除非case
,否则 case
会落到下一个break
请查看The switch Statement了解详情
答案 1 :(得分:0)
某些整数除法怎么样?
switch( (month + 2) / 12 ) {
case 1:
// winter
break;
case 2:
// spring
break; // WOOHOO SPRING BREAK!
case 3:
// summer
break;
case 4:
// fall
break; // winter is coming...
default:
break;
}
答案 2 :(得分:0)
提示:
您需要两个switch语句。一个用于第一个if / else链,一个用于第二个。 (虽然你可以轻松地将两条链折叠成一条!)
Java教程here中说明了switch语句的语法。
以下声明不执行任何操作:
if ( month <= 3) ;
它说“测试月份是否小于或等于3,然后执行空语句。这是Java语法中的”gotcha!“ ...以及一些原因之一人们认为你应该总是在Java和类似语言中使用if和loop语句的大括号。