Scanner简介
scanner类中的hasNext()
介绍这个原因:从键盘输入的时候,很容易将两个方法用来判断是否输入完毕。但是,这两个是有区别的,如果用了hasNext作为判断条件,很容易跳不出循环。例如:
Scanner sc = new Scanner(System.in);
while(sc.hasNext){
int i=sc.nextInt();
}
hasNext方法这个地方就使while无法正常退出(按enter键)循环,只有通过输入“ctrl+z”来完成输入。注意,这是输入,而不是对控制台进行操作。这相当于向控制台输入一个字符,这个字符代表EOF,此时hasNext()方法返回false,循环结束。
Scanner类中的next()和nextLine()方法
在输入的时候,比较常用,因此这个地方介绍一下这两个方法:
ArrayList的遍历方式
ArrayList有三种遍历方式,这三种方式分别是:
- 初始准备
ArrayList<Integer> a = new ArrayList<Integer>();
addData(a);
void addData(ArrayList a){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
a.add(sc.nextInt());
}
}
- Iterator类遍历
System.out.print("Iterator的遍历方式:");
for (Iterator<Integer> list = lists.iterator(); list.hasNext();) {
System.out.print(list.next());
}
for循环
``` System.out.print("for循环的遍历方式:"); for (int i = 0; i < lists.size(); i++) { System.out.print(lists.get(i)); } System.out.println(); ```
- 另一种for循环
System.out.print("foreach的遍历方式:"); for (Integer list : lists) { System.out.print(list); } System.out.println();
- 另一种for循环
冒泡排序
- 冒泡的思想:
每次都把最大的选出来,放到最后,两两比较。 - 代码文件1(Main.java)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("please input the data,press \"CTRL+Z\" to end input");
ArrayList<Integer> a = new ArrayList<Integer>();
while(sc.hasNext()){
int temp;
temp= sc.nextInt();
a.add(temp);
}
new Function().showAll(a);
new Function().BubbleSort(a);
new Function().showAll(a);
}
}
- 代码文件2(Function.java)
import java.util.ArrayList;
import java.util.Iterator;
public class Function {
void BubbleSort(ArrayList<Integer> a){
int temp;
if(a.size()!=0){
for(int i=1;i<a.size();i++){
for(int j=0;j<a.size()-i;j++){
if(a.get(j)>a.get(j+1)){
temp=a.get(j+1);
a.set((j+1), a.get(j));
a.set(j, temp);
}
}
System.out.println("the"+(i)+" th time data");
for(int m=0;m<a.size();m++){
System.out.print(a.get(m)+"\t");
}
System.out.println();
}
}
else{
System.out.println("the input array is null");
}
}
void showAll(ArrayList<Integer> a){
System.out.println("please show the data");
Iterator<Integer> it = a.iterator();
while(it.hasNext()){
System.out.print(it.next()+"\t");
}
System.out.println();
}
}
- 演示结果: