如何根据用户输入在循环中声明无限变量?

时间:2018-06-30 14:56:31

标签: java eclipse

我正在eclipse中构建一个程序,我想做一个循环,在该循环中根据用户输入声明变量。 例如,第一个输入存储在a1中,下一个输入存储在a2中,下一个输入存储在a3中,依此类推,直到用户键入数字input.hasNextDouble()以外的任何内容。

我尝试使用while循环和带有Scanner语句的if/else类进行此操作。但无法弄清楚。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以使用 HashMap

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    Map<String, Double> inputs = new HashMap<String, Double>();

    boolean isNumber = true;
    int count = 1;
    while(isNumber) {
      System.out.printf("Please enter a%d:", count);
      if(scanner.hasNextDouble()) {
        inputs.put("a" + count,  scanner.nextDouble());
        count++;
      } else {
        isNumber = false;
      } 
    }

    System.out.println("Inputs: " + inputs);

    // Auxiliary code for question in comments below
    double sum = 0.0f;
    for (double d : inputs.values()) {
      sum += d;
    }

    System.out.println("Sum: " + sum);

    for (Map.Entry<String, Double> entry : inputs.entrySet()) {
      System.out.println("Sum - " + entry.getKey() + " = " + (sum  - entry.getValue()));
    }
  }
}

用法示例:

Please enter a1: 5.5
Please enter a2: 6
Please enter a3: 7.2
Please enter a4: x
Inputs: {a1=5.5, a2=6.0, a3=7.2}
Sum: 18.7
Sum - a1 = 13.2
Sum - a2 = 12.7
Sum - a3 = 11.5