Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
} }
我想要用户输入的每个数字,但我该怎么做呢? 例如,如果输入是 2,然后是 3,然后是 4,我如何获取它们并在下一行中打印它们,同时说明它们的平均值。
最佳答案
您编写的代码存在一些问题。
if (amount == amount)
与if (true)
相同,因此您不妨将其删除。- 您无缘无故地加倍输入。
- 您正在尝试构建一个数组来存储该数量,在知道它需要有多大之前。
- 您的外部
for
循环只循环一次,因此您也不需要它。
这是代码的工作和简化版本。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
更新:上面的代码将计算用户提供的数字的平均值。
OP 似乎暗示他想要每个输入的比例。下面是使用 HashMap
来完成此操作的修改。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
关于java - 我需要找到用户输入的特定变量,但我不明白如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23096486/