【问题标题】:Automatically fill and array with a loop without a prompt..在没有提示的情况下使用循环自动填充和排列..
【发布时间】:2015-03-01 22:57:06
【问题描述】:

我想知道是否可以使用循环来填充和排列而不提示用户输入? 我必须设计一个程序来用 7 的倍数填充大小为 6 的数组。规范没有说明提示用户,而是说“使用循环填充数组”,所以我不能硬编码中的数字。 在 7 的倍数中,我需要打印出哪些可以被 3 整除。

是否可以在没有用户输入的情况下填充数组? 我的代码在下面...

import java.util.Scanner;
/**
 * Created by IntelliJ IDEA.
 * Date: 26/02/2015
 * Time: 15:25
 * UPDATE COMMENT ABOUT PROGRAM HERE
 */
public class Array7Mult
{
   public static void main(String[] args)
   {

      int multipleSeven [] = new int[6];
      final int HOWMANY=6,DIVIDE=3;
      Scanner keyboard = new Scanner(System.in);


      for(int count=0;count<HOWMANY;count++)
      {
         System.out.println("Please enter a multiple of 7 below..");
         multipleSeven[count]=keyboard.nextInt();
      }//for


      System.out.println("The multiples of seven that can be divided by 3 are..");

      for(int count=0;count<HOWMANY;count++)
      {

         if (multipleSeven[count] % DIVIDE == 0)
         {

            System.out.println(multipleSeven[count]);
         }//if
      }//for

   }//main
}//class

【问题讨论】:

  • 为什么需要用户输入来填充数组?只需使用循环来填充数组中的每个元素,例如:multipleSeven[count]=count*7;
  • int multipleSeven []discoraged 使用 int[] multipleSeven 进行声明。

标签: java arrays loops


【解决方案1】:

当然可以。假设您想用一个变量填充一个数组,该变量每个索引递增一个。说变量i(所以我们使用在循环中实例化的同一个变量)。

for(int i = 0; i < arr.length; i++)
    arr[i] = i;

就这么简单。您当然可以创建一个全局变量并将其添加到循环边界内的数组中,并在循环内操作其值。

int a = 0;

for(int i = 0; i < arr.length; i++) {
     arr[i] = a;
     a += 10;
}

如果您想将值增加为 7 的倍数,您可以简单地使用第一个示例,而不是执行 arr[i] = i 执行 arr[i] = i*7

【讨论】:

    【解决方案2】:

    使用

    for(int count=0;count<HOWMANY;count++)
        multipleSeven[i]=(i+1)*7;
    

    代替

    for(int count=0;count<HOWMANY;count++)
    {
        System.out.println("Please enter a multiple of 7 below..");
        multipleSeven[count]=keyboard.nextInt();
    }
    

    用值7,14,21,28,35,42 填充数组multipleSeven

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      相关资源
      最近更新 更多