小白求助 如何用array和enum写下面这个程序
本帖最后由 匿名 于 2021-9-15 11:56 编辑程序是下面的样子
命令不区分大小写
列表不包含100个值
import java.util.Scanner;
public class ArrayEnum {
public static void main(String[] args){
//填写程序
final Scanner scanner = new Scanner(System.in);
while(ture){
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 = newValue;
index++;
break;
case LIST:
printList(values,index);
break;
case SUM:
System.out.println(getSum(value,index));
break;
//填写程序
}
}
scanner.close();
}
//填写程序
}
最后的输出结果
ADD 10
add20
LIST
10 20
Sum
30
Add 30
suM
60
Max
30
Min
10
Summ
Invail Command
list
10 20 30
Quit
Bye! 枚举类:
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;
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 = 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;
}
private static int getMin(int[] value) {
Arrays.sort(value);
return value;
}
private static int getSum(int[] value, int index) {
int sum = 0;
for (int i = 0; i < index; i++) {
sum += value;
}
return sum;
}
private static void printList(int[] value, int index) {
for (int i = 0; i < index; i++) {
System.out.print(value+" ");
}
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;
}
}
效果图:
页:
[1]