用户输入:
import java.util.Scanner;
public class java_05 {
public static void main(String[] args) {
// 构造Scanner类的对象scan,接收从控制台输入的信息
Scanner scan = new Scanner(System.in);
System.out.println("请输入你的名字:");
String name = scan.nextLine();// nextLine()方法接收一个字符串
System.out.println("请输入你的年龄:");
String age;
while (scan.hasNextLine()){//hasNextLine()方法判断当前是否有输入,有输入则向下执行
if (scan.hasNextInt()){//判断输入的值是否为整数类型
age = scan.nextLine();//获取当前输入
System.out.println("你的姓名为:"+name);
System.out.println("你的年龄为:"+age);
break;
}else{
System.out.println("请输入数字哦~~~");
age = scan.nextLine();
continue;
}
}
}
}
结果:
输入多个整数,输入-1时退出,然后计算最大值
import java.util.*;
public class java_05 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入一个整数:");
int number = scan.nextInt();//nextInt()从键盘读取下一个整数
List arr = new ArrayList();//ArrayList底层是用数组实现的,可以认为ArrayList是一个可改变大小的数组。随着越来越多的元素被添加到ArrayList中,其规模是动态增加的。
while (number!=-1){//当输入不为-1时,可以无线输入,输入-1,则循环结束
arr.add(number);//add将指定元素添加到集合的末尾
scan = new Scanner(System.in);
System.out.println("请继续输入一个整数:");
number = scan.nextInt();
}
int max = 0;
int min = 0;
if(arr.size()>0){//size()用于获取ArrayList的大小,返回集合中的元素个数
max = (int) Collections.max(arr);
min = (int) Collections.min(arr);
}
System.out.println("最大的整数是:"+max);
System.out.println("最小的整数是:"+min);
}
}
ArrayList的常用方法如下:
ArrayList<Double> arraylist = new ArrayList<Double>();
1. arraylist.add(1.0);
:单纯的add表示从结尾加入元素
2. arraylist.size();
:size()能求出所含元素的个数
3. arraylist.remove(1);
:remove(1)表示删去第1个元素,注意计数从0开始
4. arraylist.remove(arraylist.size() - 1);
:删去最后一个元素
5. arraylist.add(0, 1.8888);
:在第0个位置 加入 1.8888这个元素
6. arraylist.set(0, 9.0);
:把第0个位置这个元素 改为 9.0
7. Collections.sort(arraylist);
:如果arraylist不是抽象类型,则支持排序
8. arraylist.get(i);
:得到第i个位置的元素值,注意从0开始计数。
Collections:
【Collections 】是一个操作 Collection(Set、 List )和 Map 等集合的工具类
Collection和【Collections】的区别?
Collection是用来存储单列数据的集合接口,常用子接口有List和Set
【Collections】是操作Collection的工具类。
那么Collections具体有哪些常用方法呢?
具体参考优秀博主的博客:Java中Collections类详细用法_南 墙-CSDN博客