bzu-java(四)

本文介绍了两个Java程序示例,分别演示了如何验证三个整数能否构成三角形的条件及如何处理用户输入的异常情况,包括输入非整数和超过数组范围的问题。

725061-20171101180735732-1775570452.png

import java.util.Scanner;

public class test {
 public static void main(String args[])
 {  int a,b,c;
    Scanner s=new Scanner(System.in);
    a=s.nextInt();
    b=s.nextInt();
    c=s.nextInt();
    test t=new test();
    try{
        t.triangle(a,b,c);
        
    }
    catch(IllegalArgumentException e ){
        e.printStackTrace();
        e.getMessage();
    }
 }
 void triangle(int a,int b,int c){
     if((a+b)<c||(a+c)<b||(b+c)<a) 
             throw new IllegalArgumentException("不能构成三角形");
     else  System.out.println(a+" "+b+" "+c);
 }
}

725061-20171101180748920-42522346.png

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.regex.Matcher;

public class test2 {
public static void main(String args[]){
    Scanner s=new Scanner(System.in);
    int[] shuzu=new int[5];
    int i=0,shuzhi=s.nextInt();
    try{
        while(shuzhi!=0){
            shuzu[i]=shuzhi;
            shuzhi=s.nextInt();
            i++;
        }
    
        
    }
    catch(InputMismatchException e){
        System.out.println("请输入整数");
        
    }
    catch(ArrayIndexOutOfBoundsException e){
        System.out.println("请输入5个整数");
    }
    finally{
        System.out.println("欢迎使用本程序");
    }
        
}
}

转载于:https://www.cnblogs.com/ysy521/p/7767764.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值