1.try{ }catch(){ }的用法
public class ExceptionTest {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("分母不能为零!");
}
}
}
运行结果为:
2.自定义余额不足异常
RuntimeException类:
public class InsufficientBalance extends RuntimeException {
public InsufficientBalance(String msg) {
super(msg);
}
}
Test类:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int num = 100;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的取款金额:");
int money = scanner.nextInt();
if (money <= num) {
num = num - money;
System.out.println("取款成功!");
} else {
throw new InsufficientBalance("余额不足!");
}
}
}
测试结果1:
测试结果2:
3.输出目录下所有以“png”为后缀的文件的绝对路径
import java.io.File;
public class pictureTest {
public static void main(String[] args) {
File file = new File("D:\\picture");
search(file);
}
public static void search(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f1 : files) {
if (f1.isFile() && f1.getName().endsWith("png")) {
System.out.println(f1.getAbsolutePath());
} else {
search(f1);
}
}
}
}
}
运行结果为:
、
4.将所有以“png”为后缀的文件改为以“jpg”为后缀的文件
import java.io.File;
public class ReNameTest {
public static void main(String[] args) {
File file = new File("D:\\picture");
System.out.println("修改前的文件绝对路径为:");
search(file);
reName(file);
System.out.println("修改后的文件绝对路径为:");
search(file);
}
public static void search(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f1 : files) {
if (f1.isFile()) {
System.out.println(f1.getAbsolutePath());
} else {
search(f1);
}
}
}
}
public static void reName(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f1 : files) {
if (f1.isFile() && f1.getName().endsWith("png")) {
String absolutePath = f1.getAbsolutePath();
String substring = absolutePath.substring(0, absolutePath.lastIndexOf("."));
File f2 = new File(substring + ".jpg");
f1.renameTo(f2);
} else {
reName(f1);
}
}
}
}
}
运行结果为: