我必须设计并实现一个程序,该程序计算用户输入的整数值数。生成一个表,列出您从输入中标识为整数的值。提供数字的总和和平均值。这是我到目前为止所做的。
public class Table {
public static void main(String [] strAng) {
int sum = 0;
double average;
int min = 1;
int max = 10;
for(int number = min;
number <= max; ++number) {
sum += number;
}
System.out.print("Sum:" +sum);
System.out.print("Average:" +average);
答案 0 :(得分:1)
你没有得到用户的意见,也没有做任何事情来平均。
试试此代码,如果您有其他要求,请更新问题。
int sum = 0;
double average;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Please enter the integers with space between each two integer: ");
String inputNumberFilePath = userInputScanner.nextLine();
String[] numStrArray = inputNumberFilePath.split(" ");
for (String string : numStrArray) {
sum += Integer.parseInt(string);
}
average = (double) sum / (double) numStrArray.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
输出样本:
Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0
答案 1 :(得分:0)
我不确定这是否正是您正在寻找的但它可能是。使用此代码,您可以在其中输入一个带整数&#34;的字符串&#34;。整数被提取,计数并且具有总和&amp;基本上是条形图执行的平均操作。希望这会有所帮助。
import java.util.*;
public class Table {
此部分用于读取包含的任何用户输入字符串。
public static String getInput(){
String outPut = "";
System.out.println("Type something to parse: ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextLine()) {
outPut = sc.nextLine();
}
return outPut;
}
在这里,我们构建我们的&#34;条形图&#34;:
public static Map<Long,Integer> makeTable(String input){
Map<Long,Integer> table = new HashMap<>();
long in = Long.parseLong(input);
long lastDig = 0;
int count = 1;
while(in > 0){
lastDig = in % 10;
in /= 10;
if(!table.containsKey(lastDig)) {
table.put(lastDig, count);
} else {
table.replace(lastDig,count,count+1);
}
}
return table;
}
这里我们计算总和:
public static int sum(Map<Long,Integer> table){
int sum = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
}
return sum;
}
我们得到平均值:
public static int average(Map<Long,Integer> table){
int sum = 0;
int divisor = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
divisor += table.get(key);
}
return sum/divisor;
}
public static void main(String[] args){
int sum = 0;
double average = 0;
String input = "";
input = getInput();
System.out.println("Unsanitized In: " + input);
这里提取整数位数!
input = input.replaceAll("[^\\d.]","");
Long.parseLong(input);
System.out.println("Sanitized In: " + input);
Map<Long,Integer> myMap = makeTable(input);
System.out.println(myMap);
System.out.println("Sum:" +sum(myMap));
System.out.print("Average:" + average(myMap));
}
}
我们的示例输出:asdf45313ha是:
Unsanitized In: asdf45313ha
Sanitized In: 45313
{1=1, 3=2, 4=1, 5=1}
Sum:16
Average:3