在Java中将元素添加到两个不同的数组

时间:2019-06-12 05:32:54

标签: java arrays java.util.scanner

我正在尝试将元素添加到两个数组中。我声明了双精度数组,以便它们也接受十进制数字。

我从用户那里得到7个元素并添加它们。如果用户只给出6个元素而不是7个元素,它将等待直到给出第7个元素。

如果用户只给出6个元素而不是7,则必须将第7个元素的位置设为“ 0”,然后将这些元素相加并打印总和。它不能等待第七元素。为此,我该怎么办?

        Scanner in = new Scanner(System.in);
        double a[] =new double[100];
        double b[] =new double[100];
        double suma=0,sumb=0;
        for(int i=0;i<7;i++)
        {
            a[i]=in.nextDouble();
            suma=suma+a[i];
        }
        for(int i=0;i<7;i++)
        {
            b[i]=in.nextDouble();
            sumb=sumb+b[i];
        }

2 个答案:

答案 0 :(得分:4)

我们可以使用类似的东西

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strArr[] = br.readLine().split(" ");
double a[]=new double[100];
double suma=0;
for(int i=0;i<strArr.length;i++)
{
  a[i] = Double.parseDouble(strArr[i]);
  suma += a[i];
}

这样,如果仅提供6个值,则数组将具有从索引0到5的值,其余所有值将保持为0

答案 1 :(得分:1)

您可以使用特定的定界符来排除默认的新行。这样,您可以使用hasNextDouble循环播放,直到到达行尾为止。

    Scanner in =new Scanner(System.in);
    double a[]=new double[10];
    double b[]=new double[10];
    double suma=0,sumb=0;

    //Use space as delimiter only, this accept a regex
    in.useDelimiter("[ ]+")
        .useLocale(Locale.ENGLISH);

    //Loop until the line is out of value (separated by spaces)
    for(int i=0; in.hasNextDouble(); i++)
    {
        a[i]=in.nextDouble();
        suma=suma+a[i];
    }

    //Consume the newline still in the buffer
    in.nextLine();

    //Loop until the line is out of value (separated by spaces)
    for(int i=0; in.hasNextDouble(); i++)
    {
        b[i]=in.nextDouble();
        sumb += b[i];
    }

    System.out.println("Sum of " + Arrays.toString(a) + " = " + suma);
    System.out.println("Sum of " + Arrays.toString(b) + " = " + sumb);

示例:

  

[1.1,5.4,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]的总和= 6.5
  [4.8,7.4,1.5,4.8,0.1,0.0,0.0,0.0,0.0,0.0,0.0]的总和= 18.6

请注意,如果使用文件,可以使用两个循环读取所有内容并将其放入列表中,从而可以改善这一点。

    Scanner in = new Scanner("1.4 2.2 3.1\n1.8 7.4 24.5");
    List<List<Double>> arrays = new ArrayList<>();

    in.useDelimiter("[ ]+")
        .useLocale(Locale.ENGLISH);

    List<Double> tmp;
    do{
        tmp = new ArrayList<>();
        arrays.add(tmp);
        while (in.hasNextDouble()) {
            tmp.add(in.nextDouble());
        }
        System.out.println(tmp);
        System.out.println(tmp.stream().mapToDouble(d -> Double.valueOf(d)).sum());
    } while (in.hasNextLine() && in.nextLine() != null);
  

[1.4,2.2]
  3.6
  [1.8,7.4,24.5]
  33.7