Java 之 实验五 -- 条件和循环语句(一)
实验五
条件和循环语句(一)
Activities at Lake LazyDays
你在Lake LazyDays度假村的工作是按照天气状况给客人提供活动建议。以下是一个活动列表:
temp >= 80: swimming;
60 <= temp < 80: tennis;
40 <= temp < 60: golf;
temp < 40: skiing.
1. 编写一段程序,提示用户输入一个气温值,然后打印出适合该气温的活动。提示:使用if-else语句,并确保你的条件设定不必过于复杂。
2. 修改程序,在temp>95或者temp < 20的情况下,打印“Visit our shops!"。提示:在条件表达式中使用布尔运算符。
import java.util.Scanner;
public class temp {
public static void main(String[] args){
System.out.println("Please number:");
Scanner Scan = new Scanner(System.in);
int temp = Scan.nextInt();
if (temp >= 80){
if (temp > 90){
System.out.println(temp + " :Visit our shops!");
}else{
System.out.println(temp + " :swimming");
}
}
else if(60<=temp & temp<80){
System.out.println(temp + " :tennis");
}
else if(40<=temp & temp<60){
System.out.println(temp + " :golf");
}
else if(temp<40){
if (temp<20){
System.out.println(temp + " :Visit our shops!");
}else{
System.out.println(temp + " :skiing");
}
}
Scan.close();
}
}
Factorials
n的阶乘(n!)表示整数从1到n的乘积。比如,4!=123*4=24。另外,0!=1。阶乘不适用于负数。
1. 编写一段程序,请用户输入一个非负整数,然后打印该整数的阶乘。请使用while循环语句编写程序。请考虑用户输入0的情况。
2. 修改程序,检查用户是否输入非负整数。如果输入的负数,则提示用户输入非负整数,并请用户重新输入,直到用户输入非负整数为止。
import java.util.Scanner;
public class Factorials {
public static void main(String[] ages){
while(true){
System.out.println("请输入一个非负整数");
Scanner Scan = new Scanner(System.in);
int num = Scan.nextInt();
if (num==0){
System.out.println(num + "! = 1");
}else if (num > 0){
System.out.println(num + "! = " + recurrence(num));
}else{
System.out.println("输入错误");
}
}
}
public static int recurrence(int num){
if(num<=1)
return 1;
else
return num*recurrence(num-1);
}
}

浙公网安备 33010602011771号