朋友李老板 给我发了一篇全英文的java系题 看得眼睛都花了 在做的过程中第10题比较有趣 我写出来分享下
Write a complete Java program that prompts the user for a series of numbers to determine the smallest value entered. Before the program terminates, display the smallest value.
就是我标题的意思
一拿到这个题我就想到了 我要做个数组 通过循环遍历来保存我keyboard输入的数字 , 然后在来一个循环 遍历数组 挨个比较大小 。遇到比他小的 就把小的赋值给min变量 。后来在敲代码的过程中 我发现我的min 还需要一个初始值 而这个初始值不可以为零
因为为零的话 那么我的判断 就会认为0是最小的 于是我的min就恒为0;思考了半宿没想出好方法 ;第二天 ;李老板高兴的给我说他拿去问老师了 ;代码是
package lilaobanTEXT20180808;
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> arrayList = new ArrayList();
int MIN = 0;
System.out.println("How many numbers do you need to type in?");
Scanner scanner = new Scanner(System.in);
int getTheLength = scanner.nextInt();//限制数组长度
for(int a = 0;a<getTheLength;a++) {
System.out.println("type in numb");
Scanner typein = new Scanner(System.in);
arrayList.add(typein.nextInt());//具体给数组赋值的语句
}//给数组赋值
System.out.println(arrayList.size());
for(int i=0;i<arrayList.size();i++)
//这里的i是位数,默认第0位开始循环,第0位小于数组长度,第i位+1位
{
if(i==0)//i是位数 判断是否数组第一位
{
MIN = (int) arrayList.get(i);
}//如果i=0,min就得到i=0这个数
else //不是数组第一位
{
if (MIN > (int)arrayList.get(i))//如果最小值 比当前数组第i位的质大 则把当前值当作最小值
{
MIN = (int)arrayList.get(i);//
}
}
}
System.out.println(MIN);
}
}
他的代码在第二个比较循环中加了 一个if语句 使我的问题就迎刃而解
拜读拜读
ArrayList数组我也是第一次见
这个数组高级了 是自动数组 可以自动改变大小
他的初始化有3种形式
1)不初始化容量 ArrayList al = new ArrayList();//默认容量为0,当数组容量满时数组会自动一当前数组容量的2倍扩容
2)初始化容量ArrayList al = new ArrayList(3);//初始容量为3
3)以一个集合或数组初始化ArrayList al = new ArrayList(a);//a为集合或数组
他具有自己的增删改语句
1)增加
ArrayList al = new ArrayList();
al.add("a");
2)删除
al.Remove(object obj);//移除数组中的obj元素