【问题标题】:A program asks to enter 10 values and sum them一个程序要求输入 10 个值并将它们相加
【发布时间】:2021-03-03 13:47:10
【问题描述】:

使用(对于每个)我想要一个程序要求输入 10 的倍数中的 10 个值,并将其存储在一个数组中,并找到在这个数组中输入的这些数字的总和......问题是代码只有处理我输入的最后一个元素The problem photo

package lesson27task2Pac;
import java.util.Scanner;
public class Lesson27Task2 {

    public static void main(String[] args) {

    // TODO Auto-generated method stub
    

  
    int larr;
    Scanner scw = new Scanner(System.in);
    System.out.println("Enter Aarray Lenght :");
    larr=scw.nextInt();
    
    int [] array = new int [larr];
    
    
    Scanner sce = new Scanner(System.in);
    System.out.println("Enter multiples :=====>");

    for (int e : array) {
    array[e] = sce.nextInt();
    }

    for (int e: array) {
        
        if (e % 10 == 0) {
            System.out.println(e +"");
        } else {
            System.out.println("Not a multiple !!!");
        }
    
    }
    int sum = 0 ;
    for (int e : array) {
        sum = sum + e;
    }
    System.out.println("Summation of array elements : "+sum);}}

【问题讨论】:

    标签: java eclipse for-loop foreach eclipse-cdt


    【解决方案1】:

    这种类型的foreach循环

    for (int e : array) {
       array[e] = sce.nextInt();
    }
    

    正在返回数组的值并将其放入值e

    由于数组只有0的默认值,所以你一直在做

    array[0] = sce.nextInt();
    

    尝试使用普通的 for 循环

    for (int e = 0; e < array.length; e++)
    {
        array[e] = sce.nextInt();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2015-05-14
      相关资源
      最近更新 更多