Week02Day02 Java

package com.zhongruan.demo;

import java.util.Scanner;

public class Demo1 {
    public static void main(String[] args) {
        /*
            模拟简单计算器,可以运算+,—,*,/,%。
            - 接收三个参数,一个整数,一个运算符,另一个整数。
            - 计算出运算结果。
            - 无法运算时,返回null。
         */
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        String b = sc.next();
        int c = sc.nextInt();
        String count = count(a, b, c);
        System.out.println(a + b + c + "=" + count);
    }

    private static String count(int a, String b, int c) {
        int count = 0;
        if("+".equals(b)) {
            count = a + c;
        } else if ("-".equals(b)){
            count = a - c;
        }else if ("*".equals(b)){
            count = a * c;
        }else if ("/".equals(b)){
            count = a / c;
        }else if ("%".equals(b)){
            count = a % c;
        } else{
            return null;
        }
        return count + "";

    }
}

package com.zhongruan.demo;

import java.io.FileNotFoundException;
import java.io.IOException;

public class Demo3 {
    public static void main(String[] args) throws IOException {
        String path = "a.text";
        read(path);
    }

    private static void read(String path) throws FileNotFoundException, IOException {
        if ("".equals(path)) {
            throw new FileNotFoundException("path为空");
        }
        if("b.text".equals(path)){
            throw new IOException();
        }
    }
}

package com.zhongruan.demo;

import com.zhongruan.exception.RegisterException;

public class Demo5 {
    private static String[] names = {"Tony", "Ned", "Robbert", "John"};
    public static void main(String[] args) {
        try{
            checkUserName("Tony");
            System.out.println("注册成功");
        }catch (RegisterException e) {
            e.printStackTrace();
        }

    }

    private static void checkUserName(String s) throws RegisterException {
        for (String name : names ) {
            if(s.equals(name)){
                throw new RegisterException("该用户名已存在");
            }
        }

    }
}
package com.zhongruan.demo;

import javax.xml.bind.Element;

public class Demo4 {
    public static void main(String[] args) {
        //定义了一个数组
        int[] arr = {2, 4, 6};
        int index = 3;
        try{
            int element = getElement(arr, index);
            System.out.println(element);
        } catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }
        System.out.println("over");
    }

        private static int getElement(int[] arr, int index) {
            if(index >= arr.length){
                throw new ArrayIndexOutOfBoundsException("数组索引越界啦!!!!");
            }
            int element = arr[index];
            return element;
    }
}

你可能感兴趣的:(Week02Day02 Java)