有大神帮我写50行包括3个函数和循环语句的Java代码嘛? 20
1个回答
展开全部
你们是不是有作业啊,问得问题都差不多啊,我改动了一下,加入了一个回溯函数求阶乘的,如下:
import java.util.ArrayList;
import java.util.Scanner;
public class LoopAndFunction {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Long number;
ArrayList<Long> theList = new ArrayList<Long>();
System.out.print("Enter a number for list, end with negative number: ");
number = input.nextLong();
while(number >= 0){
theList.add(number);
System.out.print("Enter a number for list, end with negative number: ");
number = input.nextLong();
}
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++){
Long eachNumber = theList.get(i);
if(isOddNumber(eachNumber)){
System.out.println(eachNumber + " is odd number");
System.out.printf("it's factorial is: %d\n", factorial(eachNumber));
}
else{
System.out.println(eachNumber + " is even number");
System.out.printf("it's factorial is: %d\n", factorial(eachNumber));
}
}
}
public static boolean isOddNumber(Long number){
boolean isOdd = false;
if(number % 2 == 1){
isOdd = true;
}
return isOdd;
}
public static void sortArray(ArrayList<Long> list){
for(int i = 0; i < list.size() - 1; i++){
Long 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);
}
}
}
}
public static Long factorial(Long n){
if(n == 0 || n == 1){
return 1L;
}
return n * factorial(n - 1);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询