嘿,伙计们,我不知道答案是否存在,我不太知道如何描述我的问题。我在这里看了大约45分钟,找不到回答我问题的东西。所以如果它已经被发到其他地方了,我很抱歉。
我需要能够在一条线上输入一系列数字,并取6到10之间的数字,并找出6-10之间的平均值和最大值。
例子:4 5 6 6 7 7 7 8 8 8 9 9和:8 6 3 10
问题是,我已经找到了答案,如果你想得到X的输入量,但我正在做的任务是输入任何地方,从1-20个数字在一条线上。
我不能使用Array来完成我的任务,我希望我可以这样做,因为它会使事情变得更简单。我完全不知所措。
谢谢你的帮助!
发布于 2015-02-27 08:37:43
如果您的输入是带有空格的字符串,您可以这样做
String string = "4 5 6 6 7 7 7 8 8 8 8 9 9 9";
List<String> splittedStrings = Arrays.asList(string.split(" "));
在此之后,您将得到一个包含拆分输入的列表,您可以以您想象的任何方式处理这些输入(比如删除不需要的条目并对它们进行汇总)。
更新:
这样的东西即使没有数组或列表也能工作:
String string = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20";
string = string.replaceAll("16|17|17|18|19|20|[1-5](?!0)", "").trim();
System.out.println(string);
int counter = 0;
int value = 0;
int max = 0;
while (!string.isEmpty()) {
String substring = "";
if (string.indexOf(" ") == -1) {
substring = string;
string = "";
} else {
substring = string.substring(0, string.indexOf(" "));
string = string.substring(string.indexOf(" ")).trim();
}
if (!substring.isEmpty()) {
int integer = Integer.valueOf(substring).intValue();
if (integer > max) {
max = integer;
}
value = value + integer;
counter++;
}
}
System.out.println("Max: " + max + "; Average: " + Double.valueOf(value) / counter);
https://stackoverflow.com/questions/28760525
复制相似问题