Java语言 求一个程序 要有循环循环,至少两个函数,至少五十行有效代码。并求讲解。
1个回答
展开全部
刚写的,新鲜出炉
import java.util.ArrayList;
import 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的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询