public class Test15 {
/*
* 3.从键盘接受多个int型的整数,直到用户输入end结束, 要求:把所有的整数按倒序写到D:\\number.txt中
*
* 思路:
* 用nextLine接收, Integer.parseInt()转成数字, 存到list集合中, 排序list集合, 倒着遍历输出到文本中
*/
public static void main(String[] args) throws IOException {
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
// 创建List集合存入键入值
List<Integer> al = new ArrayList<>();
// 提示输入
System.out.println("请输入整数,end结束。");
// 循环
while (true) {
// 定义个line接收键入的字符串
String line;
// 判断是否是end结束语,是的话跳出循环
if ("end".equals(line = sc.nextLine())) {
break;
// 如果不是end就将值存入list集合中。
} else {
// 如果键入的不是end,又非整数。将提示输入错误!
try {
al.add(Integer.parseInt(line));
} catch (Exception e) {
System.out.println("你输入的不是整数或end");
}
}
}
// 创建输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\number.txt"));
// 倒着循环遍历进文件中。
for (int i = al.size() - 1; i >= 0; i--) {
// 用get();方法提取集合中的元素,并将其转成字符串。
bw.write(al.get(i) + " ");
}
// 关闭流。
bw.close();
}
} |
|