(一) 使用选择语句
1.使用 if...else 语句 • 程序功能:使用 if...else 语句构造多分支,首先判断输入的年份是否合法(年份位于 1000 和 9999 之间),然后判断某一年是否为闰年。闰年的条件是符合下面二者之一:能被 4 整除,但不能被 100 整除;能被 4 整除,又能被 100 整除。
源码:
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
int a=0;
Scanner io =new Scanner(System.in);
int year=io.nextInt();
if(year<1000||year>9999)
System.out.print("输入年份不合法");
else
{
if(year%4==0)
if(year%100==0)
{
if(year%400==0)
a=1;
}
else a=1;
if(a==1)System.out.print("该年分是闰年");
else System.out.print("该年分不是闰年");
}
}
}
运行结果:
2.使用 switch 语句 • 程序功能:在不同温度时显示不同的解释说明。温度在 0--10℃ 提示“有点冷。要多穿 衣服”,10--30 提示“正合适。出去玩吧”,30 以上提示“太热了!开空调”。
源码:
import java.util.Scanner;
public class Temperature {
public static void main(String[] args) {
int temperature;
Scanner io=new Scanner(System.in);
temperature=io.nextInt();
switch(temperature/10)
{
case 0:System.out.print("有点冷。要多穿衣服");break;
case 1:
case 2:System.out.print("正合适。出去玩吧");break;
default:System.out.print("太热了!开空调");break;
}
}
}
运行结果:
(二) 使用循环语句
1. for 循环语句练习 • 程序功能:编写 Java 程序,应用 for 循环打印菱形。
源码:
public class PrintDiamond {
public static void main(String[] args)
{
for(int i=1;i<=4;i++)
{
for(int j=0;j<=3-i;j++)
System.out.print(" ");
for(int j=1;j<=2*i-1;j++)
{
if(j==1||j==2*i-1)
System.out.print("+");
else System.out.print(" ");
}
System.out.println();
}
for(int i=1;i<=3;i++)
{
for(int j=i;j>0;j--)
System.out.print(" ");
for(int j=1;j<=7-2*i;j++)
{
if(j==1||j==7-2*i)
System.out.print("+");
else System.out.print(" ");
}
System.out.println();
}
}
}
运行结果:
2. while 和 do…while 循环语句练习 • 程序功能:求 1+2+…+100 之和,并将求和表达式与所求的和显示出来。
源码:
public class Sum100 {
public static void main(String[] args)
{
int i=0,sum=0;
// while(i<=100)
// {
// sum+=i;i++;
// }
do
{
sum+=i;
i++;
}
while(i<=100);
System.out.print("1+2+...+100=");
System.out.print(sum);
}
}
运行结果:
(三)使用异常处理
设计程序,根据三角形的三条边求三角形的面积。当三条边的数据不能构成三角形时, 抛出异常。
源码:
import java.util.Scanner;
class Triangle {
float a, b, c;
void area(float a, float b, float c) {
float p = (a + b + c) / 2;
System.out.print(Math.sqrt(p * (p - a) * (p - b) * (p - c)));
}
}
class MyException extends Exception {
public MyException(String message) {
super(message);
}
public MyException() {
super("三角形数据错误");
}
}
public class TriangleException {
static void f(float a,float b,float c) throws MyException {
if(a+b<=c||a+c<=b||b+c<=a)
throw new MyException();
}
public static void main(String []args)
{
try{ Triangle Triangle1;
Triangle1=new Triangle();
Scanner io=new Scanner(System.in);
Triangle1.a=io.nextFloat();
Triangle1.b=io.nextFloat();
Triangle1.c=io.nextFloat();
f(Triangle1.a,Triangle1.b,Triangle1.c);
Triangle1.area(Triangle1.a, Triangle1.b, Triangle1.c);
}
catch(MyException ex)
{
System.out.println(ex);
}
}
}
运行结果: