1、编写一个程序,提示用户输入两个整数,然后显示它们的和。程序应该在输入不正确时提示用户再次读取数值。
import java.io.*;
public class Add {
public static void main(String[] args) throws IOException {
while (true) {
try {
BufferedReader br_1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入整数一:");
String str_1 = br_1.readLine(); // 获取键盘输入
int int_1 = Integer.parseInt(str_1); // 转整形
BufferedReader br_2 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入整数二:");
String str_2 = br_2.readLine(); // 获取键盘输入
int int_2 = Integer.parseInt(str_2); // 转整形
int int_sum;
int_sum = int_1 + int_2;
System.out.println("和为:" + int_sum);
}
catch(NumberFormatException e) { // 转格式出现错误就会转到此
System.out.println("输入错误,请输入整数");
}
}
}
}
2、
编写一个满足下列要求的程序:
- 创建一个由100个随机选取的整数构成的数组。
- 提示用户输入数组的下标,然后显示对应的元素值。如果指定下标越界,则显示消息“Out of Bounds“。
import java.io.*;
import java.util.Random;
public class Select {
private static int GetRandom(int min, int max) {
Random n = new Random(); // 新建random类型变量并初始化
return n.nextInt((max - min) +1) + min; // 生成一个随机数, +min可以阻止其小于min
}
public static void main(String[] args) throws IOException {
while (true) {
try {
BufferedReader br_1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入随机数生成范围的最小值:");
String str_1 = br_1.readLine(); // 获取键盘输入
int min = Integer.parseInt(str_1); // 转整形
BufferedReader br_2 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入随机数生成范围的最大值:");
String str_2 = br_2.readLine(); // 获取键盘输入
int max = Integer.parseInt(str_2); // 转整形
int listn[] = new int[100];
if (min >= max) {
System.out.println("最大值需要大于最小值"); // 需要范围大小核查
} else {
for (int i = 0; i < 100; i++) {
int item = GetRandom(min, max); // 循环生成随机数
listn[i] = item; // 写入数组
}
}
BufferedReader br_3 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入索引查找元素:");
String str_3 = br_3.readLine(); // 获取键盘输入
int index = Integer.parseInt(str_3); // 转整形
System.out.println(listn[index]); // 根据索引查元素
}
catch (ArrayIndexOutOfBoundsException e) { // 索引超出限制异常处理
System.out.println("Out of Bounds");
}
}
}
}
3、编写一个程序,提示用户输入一个目录名称,然后使用File的mkdirs方法创建相应的目录。如果目录创建成功则显示”Directory created successfully”,如果目录已经存在,则显示“Directory already exists“。
import java.io.*;
public class CreateCatalogue {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入目录名称");
String str = br.readLine(); // 获取键盘输入
File file = new File(str); // 新建目录,文件目录名为str
if (file.mkdirs()) { // 如果创建成功返回true
System.out.println("Directory created successfully.");
} else { // 如果已有文件返回false
System.out.println("Directory already exists.");
}
}
}