Java 遍历数组

Java 遍历数组,java,arrays,Java,Arrays,这是一些关于数组的家庭作业问题,我有问题,所以没有答案,请给出提示 编写一个程序,生成一个由20个随机整数组成的数组,值为1-100,然后计算数组中哪三个连续元素的和最大 对于这个问题,我的问题是如何以块而不是单个值遍历数组 到目前为止,我得到的是: public class Arrays { public static void main (String[] args) { int[] randNum = new int[21]; for (in

这是一些关于数组的家庭作业问题,我有问题,所以没有答案,请给出提示

  • 编写一个程序,生成一个由20个随机整数组成的数组,值为1-100,然后计算数组中哪三个连续元素的和最大
  • 对于这个问题,我的问题是如何以块而不是单个值遍历数组

    到目前为止,我得到的是:

    public class Arrays
    {
        public static void main (String[] args)
        {
            int[] randNum = new int[21];
            for (int i = 1; i < randNum.length; i++)
            {
                randNum[i] = (int) (Math.random() * 100) + 1;
                System.out.print(randNum[i] + ", ");
            }
    
                System.out.println();
                int index = 0;
                for(int x : randNum)
                    System.out.println((index++) + ": " + x);
    }
    
    公共类数组
    {
    公共静态void main(字符串[]args)
    {
    int[]randNum=新int[21];
    for(int i=1;i
    这只是用随机数填充数组并列出索引数。我如何以3个相邻的数字循环数组

  • 编写一个程序,生成一个由10个随机小写字母组成的数组,字符串长度在5到50之间是随机的。然后,它继续计算字符串中每个字母的出现次数,并打印出这些计数。最后,它将打印字符串的平均长度
  • 我的问题是如何计算单个字母在所有数组中出现的次数。

    以下是一些提示:

    问题1

    在阵列上循环,从位置1开始,使用计数器p转到位置18 对于每个位置,将
    p
    p-1
    p+1
    处的值相加。如果该值大于最后计算的值,则存储索引

    问题2 使用键类型为字符、值类型为整数的hashmap。对于数组中每个字符串的每个字母,检查它是否在hashmap中,如果不在,则在hashmap中放入一个条目并将其值设置为1。这实际上是在生成字符的直方图。

    对于问题2

     public static void main(String[] args) {
        // TODO Auto-generated method stub
       String inp="hsaadhiewhuwccwecwec";
        HashMap<Character, Integer> countcharact=new HashMap<>();
        int j=0;
        for(int i=0;i<inp.length();i++){
            if(countcharact.containsKey(inp.charAt(i))==true){
                j=countcharact.get(inp.charAt(i));
                countcharact.put(inp.charAt(i),j+1);
    
            }
            else
                countcharact.put(inp.charAt(i), 1);
        }
    
        Set<Character> s=countcharact.keySet();
        for(Character c:s){
            System.out.println(c+" "+countcharact.get(c)+" times");
        }
    
    }
    
    publicstaticvoidmain(字符串[]args){
    //TODO自动生成的方法存根
    字符串inp=“hsaadhiewhuwcwecwec”;
    HashMap countcharact=新HashMap();
    int j=0;
    对于(int i=0;i
    publicstaticvoidmain(String[]args){
    //TODO自动生成的方法存根
    int[]输入={1,2,4,5,2,9,2};
    int p=0,最大值=0,起始值=0;;
    while(最大值){
    开始=p;
    最大值=输入[p]+输入[p+1]+输入[p+2];
    }
    p++;
    }
    对于(int i=开始;iProb 1:
    您可以做的是创建另一个方法,该方法接受数组并返回三个连续索引中的第一个索引

        int compute(int[] array)
        { 
              int temp=0;
              int index;
              for(int i=0; i<=17; i++)
              {
                  if( array[i]+array[i+1]+array [i+2]>temp)
                  {
                  temp=  array[i]+array[i+1]+array [i+2];
                  index=i;
                  }
               }
               return index;
               // you can now use this index and compute
               // next two indexes
        }
    
    int计算(int[]数组)
    { 
    内部温度=0;
    整数指数;
    对于(int i=0;itemp)
    {
    温度=阵列[i]+阵列[i+1]+阵列[i+2];
    指数=i;
    }
    }
    收益指数;
    //现在可以使用此索引并计算
    //下两个索引
    }
    
    问题1 您需要一个包含20个元素的数组,一个随机生成器用随机数填充数组,然后一个带有if语句的for循环来确定哪三个连续元素的和最大

    问题2 您将需要一个包含10个元素的数组,一个包含字母表中每个字母的字符串,一个随机生成器来用字母表中的随机字母填充数组,一个将随机字符串作为外部贴图键的贴图,一个将字符串中的字母作为键,并将其计数作为值的贴图

    public static void main(String[] args) throws Exception {
        problem1();
        problem2();
    }
    
    private static void problem1() {
        Random r = new Random(System.currentTimeMillis());
    
        int[] randomNumbers = new int[20];
        // Populate your array with random numbers;
        for (int i = 0 ; i < randomNumbers.length; i++) {
            // This will generate numbers from 1 - 100
            randomNumbers[i] = r.nextInt(100) + 1;
        }
    
        int[] consecutiveElements = null;
        int largestSum = 0;
    
        // -3 because we're looking 3 elements at a time and we don't want to go outside the bounds of the array
        for (int i = 0; i < randomNumbers.length - 3; i++) {
            int sum = randomNumbers[i] + randomNumbers[i + 1] + randomNumbers[i + 2];
            if (sum > largestSum) {
                largestSum = sum;
                consecutiveElements = new int[] { randomNumbers[i], randomNumbers[i + 1], randomNumbers[i + 2] };
            }
        }
    
        System.out.println("Problem 1:");
        System.out.println("Random numbers: " + Arrays.toString(randomNumbers));
        System.out.println("Largest consecutive elements for sum: " + Arrays.toString(consecutiveElements));
        System.out.println("Sum: " + largestSum);
    }
    
    private static void problem2() {
        Random r = new Random(System.currentTimeMillis());
        String[] randomStrings = new String[10];
    
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
    
        // Populate your strings with random letters
        for (int i = 0; i < randomStrings.length; i++) {
            randomStrings[i] = "";
            // To get a number from 5 - 50;
            int randomLength = r.nextInt(46) + 5;
            for (int j = 0; j < randomLength; j++) {
                randomStrings[i] += alphabet.charAt(r.nextInt(26)); 
            }
        }
    
        // Count occurrences of letters in each string and sum up the string lengths
        int stringLengthSum = 0;
        // Map of Maps...  Outer map is keyed by the random strings with an inner map of the characters and their occurrences as the value
        // Inner map is keyed by the letters in the random string with their occurrences as the value
        Map<String, Map<String, Integer>> occurrences = new HashMap<>();
        for (int stringIndex = 0; stringIndex < randomStrings.length; stringIndex++) {
            // Calculate the sum of the string lengths
            stringLengthSum += randomStrings[stringIndex].length();
    
            // Count letter occurrences in each string
            occurrences.put(randomStrings[stringIndex], new HashMap<>());
            for (int characterIndex = 0; characterIndex < randomStrings[stringIndex].length(); characterIndex++) {
                String letter = String.valueOf(randomStrings[stringIndex].charAt(characterIndex));
                if (!occurrences.get(randomStrings[stringIndex]).containsKey(letter)) {
                    occurrences.get(randomStrings[stringIndex]).put(letter, 1);
                } else {
                    int currentOccurrenceCount = occurrences.get(randomStrings[stringIndex]).get(letter);
                    occurrences.get(randomStrings[stringIndex]).put(letter, currentOccurrenceCount + 1);
                }
            } // End for (int characterIndex = 0; characterIndex < randomStrings[stringIndex].length(); characterIndex++)
        } // End for (int stringIndex = 0; stringIndex < randomStrings.length; stringIndex++)
    
        // Calculate the average string length
        double stringLengthAverage = stringLengthSum / randomStrings.length;
    
        System.out.println("");
        System.out.println("Problem 2:");
        // Print average string length
        System.out.println("Average string length: " + stringLengthAverage);
        // Print out random strings and their letter occurences
        for (Map.Entry<String, Map<String, Integer>> entry : occurrences.entrySet()) {
            System.out.println(entry.getKey());
            for (Map.Entry<String, Integer> letterEntryCount : entry.getValue().entrySet()) {
                System.out.print(letterEntryCount.getKey() + ": " + letterEntryCount.getValue() + "   ");
            }
            System.out.println("");
        }
    }
    
    publicstaticvoidmain(字符串[]args)引发异常{
    问题1();
    问题2();
    }
    私有静态无效问题1(){
    Random r=新的Random(System.currentTimeMillis());
    int[]随机数=新的int[20];
    //用随机数填充数组;
    对于(int i=0;i最大总和){
    最大总和=总和;
    连续元素=新的int[]{randomNumbers[i],randomNumbers[i+1],randomNumbers[i+2]};
    }
    }
    System.out.println(“问题1”);
    System.out.println(“随机数:”+Arrays.toString(randomNumbers));
    System.out.println(“求和的最大连续元素:“+Arrays.toString(continuenceelements));
    System.out.println(“总和:+最大总和”);
    }
    私有静态无效问题2(){
    Random r=新的Random(System.currentTimeMillis());
    字符串[]随机字符串=新字符串[10];
    字符串字母表=“abcdefghijklmnopqrstuvxyz”;
    //用随机字母填充字符串
    for(int i=0;ipublic static void main(String[] args) throws Exception {
        problem1();
        problem2();
    }
    
    private static void problem1() {
        Random r = new Random(System.currentTimeMillis());
    
        int[] randomNumbers = new int[20];
        // Populate your array with random numbers;
        for (int i = 0 ; i < randomNumbers.length; i++) {
            // This will generate numbers from 1 - 100
            randomNumbers[i] = r.nextInt(100) + 1;
        }
    
        int[] consecutiveElements = null;
        int largestSum = 0;
    
        // -3 because we're looking 3 elements at a time and we don't want to go outside the bounds of the array
        for (int i = 0; i < randomNumbers.length - 3; i++) {
            int sum = randomNumbers[i] + randomNumbers[i + 1] + randomNumbers[i + 2];
            if (sum > largestSum) {
                largestSum = sum;
                consecutiveElements = new int[] { randomNumbers[i], randomNumbers[i + 1], randomNumbers[i + 2] };
            }
        }
    
        System.out.println("Problem 1:");
        System.out.println("Random numbers: " + Arrays.toString(randomNumbers));
        System.out.println("Largest consecutive elements for sum: " + Arrays.toString(consecutiveElements));
        System.out.println("Sum: " + largestSum);
    }
    
    private static void problem2() {
        Random r = new Random(System.currentTimeMillis());
        String[] randomStrings = new String[10];
    
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
    
        // Populate your strings with random letters
        for (int i = 0; i < randomStrings.length; i++) {
            randomStrings[i] = "";
            // To get a number from 5 - 50;
            int randomLength = r.nextInt(46) + 5;
            for (int j = 0; j < randomLength; j++) {
                randomStrings[i] += alphabet.charAt(r.nextInt(26)); 
            }
        }
    
        // Count occurrences of letters in each string and sum up the string lengths
        int stringLengthSum = 0;
        // Map of Maps...  Outer map is keyed by the random strings with an inner map of the characters and their occurrences as the value
        // Inner map is keyed by the letters in the random string with their occurrences as the value
        Map<String, Map<String, Integer>> occurrences = new HashMap<>();
        for (int stringIndex = 0; stringIndex < randomStrings.length; stringIndex++) {
            // Calculate the sum of the string lengths
            stringLengthSum += randomStrings[stringIndex].length();
    
            // Count letter occurrences in each string
            occurrences.put(randomStrings[stringIndex], new HashMap<>());
            for (int characterIndex = 0; characterIndex < randomStrings[stringIndex].length(); characterIndex++) {
                String letter = String.valueOf(randomStrings[stringIndex].charAt(characterIndex));
                if (!occurrences.get(randomStrings[stringIndex]).containsKey(letter)) {
                    occurrences.get(randomStrings[stringIndex]).put(letter, 1);
                } else {
                    int currentOccurrenceCount = occurrences.get(randomStrings[stringIndex]).get(letter);
                    occurrences.get(randomStrings[stringIndex]).put(letter, currentOccurrenceCount + 1);
                }
            } // End for (int characterIndex = 0; characterIndex < randomStrings[stringIndex].length(); characterIndex++)
        } // End for (int stringIndex = 0; stringIndex < randomStrings.length; stringIndex++)
    
        // Calculate the average string length
        double stringLengthAverage = stringLengthSum / randomStrings.length;
    
        System.out.println("");
        System.out.println("Problem 2:");
        // Print average string length
        System.out.println("Average string length: " + stringLengthAverage);
        // Print out random strings and their letter occurences
        for (Map.Entry<String, Map<String, Integer>> entry : occurrences.entrySet()) {
            System.out.println(entry.getKey());
            for (Map.Entry<String, Integer> letterEntryCount : entry.getValue().entrySet()) {
                System.out.print(letterEntryCount.getKey() + ": " + letterEntryCount.getValue() + "   ");
            }
            System.out.println("");
        }
    }