枚举类:package excel;
public enum Command {
ADD,LIST,SUM,QUIT,MAX,MIN;
}
代码:package excel;
import java.util.Arrays;
import java.util.Scanner;
/**
* 使用array和enum填写代码
*/
public class Test {
static int index = 0;
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
int[] value = new int[100];
while (true) {
final Command command = getCommand(scanner); //Command is enum
if (command == Command.QUIT) {
System.out.println("Bye!");
break;
}
switch (command) {
case ADD:
final int newValue = getValue(scanner);
value[index] = newValue;
index++;
break;
case LIST:
printList(value.clone(), index);
break;
case SUM:
System.out.println(getSum(value.clone(), index));
break;
case MAX:
System.out.println(getMax(value.clone()));
break;
case MIN:
System.out.println(getMin(value.clone()));
break;
default:
break;
}
}
scanner.close();
}
private static int getMax(int[] value) {
Arrays.sort(value);
return value[value.length-1];
}
private static int getMin(int[] value) {
Arrays.sort(value);
return value[100-index];
}
private static int getSum(int[] value, int index) {
int sum = 0;
for (int i = 0; i < index; i++) {
sum += value[i];
}
return sum;
}
private static void printList(int[] value, int index) {
for (int i = 0; i < index; i++) {
System.out.print(value[i]+" ");
}
System.out.println();
}
private static int getValue(Scanner scanner) {
return scanner.nextInt();
}
private static Command getCommand(Scanner scanner) {
String next = scanner.next();
String s = next.toUpperCase();
switch (s) {
case "ADD":
return Command.ADD;
case "LIST":
return Command.LIST;
case "SUM":
return Command.SUM;
case "QUIT":
return Command.QUIT;
case "MAX":
return Command.MAX;
case "MIN":
return Command.MIN;
default:
break;
}
return null;
}
}
效果图:
|