刚写的,新鲜出炉
import java.util.ArrayListimport java.util.Scanner
public class LoopAndFunction {
public static void main(String[] args){
Scanner input = new Scanner(System.in)
int number
ArrayList<Integer> theList = new ArrayList<Integer>()
System.out.print("Enter a number for list, end with -1: ")
number = input.nextInt()
while(number != -1){
theList.add(number)
System.out.print("Enter a number for list, end with -1: ")
number = input.nextInt()
}
System.out.println("the list is: " + theList.toString())
sortArray(theList)
System.out.println("after sorting, the list is: " + theList.toString())
for(int i = 0 i < theList.size() i++){
int eachNumber = theList.get(i)
if(isOddNumber(eachNumber)){
System.out.println(eachNumber + " is odd number")
}
else{
System.out.println(eachNumber + " is even number")
}
}
}
public static boolean isOddNumber(int number){
boolean isOdd = false
if(number % 2 == 1){
isOdd = true
}
return isOdd
}
public static void sortArray(ArrayList<Integer> list){
for(int i = 0 i < list.size() - 1 i++){
int temp = list.get(i)
for(int j = i + 1 j < list.size() j++){
if(list.get(i) > list.get(j)){
list.set(i, list.get(j))
list.set(j, temp)
}
}
}
}
}
讲解嘛,main方法就是调用两个方法的,通过Scanner, while循环让用户输入一些整数,以-1结束,然后先是排列数组,再使用for来挨个判断这些数字是否为偶数。isOddNumber很简单,就是判断一个整数是否为奇数,用%求余来实现。sortArray也很简单,就是排序一个整数型的list的。
int i = 0while(i <10){
System.out.println(i)
i++
}
输出结果为:0,1,2,3,4,5,6,7,8,9
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)