【问题标题】:Java How to create Array length based on user input & How to Assign a Number value to an ArrayJava 如何根据用户输入创建数组长度以及如何将数字值分配给数组
【发布时间】:2016-11-28 05:35:18
【问题描述】:

所以这个程序应该做的是,用户输入一个字符串,程序会检查每个字符从 charAt(0) 到 charAt(length of string - 1) 它会检查它是否是一个有效的字母(A-Z 或 a-z)。任何非字母都被视为单词分隔符。

每当下一个字符是字母时,计数器就会增加。一旦字符无效(数字、符号、标点符号、空格等),计数器将重置为 0,并且在无效字符之前的字符到最后一个有效字符(在这种情况下为 charAt(0) 假设)将创建单词 1。当该字符无效,它会将计数器分配给最初从索引 0 开始的数组,然后将增加索引以便可以将其分配给下一个字长。

如何根据该程序中创建的单词数创建一个数组?例如,如果我输入以下字符串,则数组的长度为 7。

8this pro98gram 是做什么的?

Word1= 什么,Word2= 是,Word3=this,Word4=pro,word5=gram,word6=doin,word7=g。

另外,每次进入程序中的else语句时,如何为特定的数组索引分配一个数字值,例如word[a],其中a为0、1、2、3、4等。

这是我到目前为止所做的。

import java.util.Scanner;

public class WordCountInString {

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

    int a = 0; // Initial index is 0;
    int[] word = new int[a]; // Creating an array.

    String string;
    System.out.print("Enter a String of Data Please: ");
    string = input.nextLine();
    
    int counter = 0;
    for (int i = 0; i < string.length(); i++) {
        
        if (string.charAt(i) >= 'a' && string.charAt(i) >= 'z' // Check to see if charAt(i) is a letter.
                || string.charAt(i) >= 'A' && string.charAt(i) <= 'Z') { 
            counter++; // Counter every time the next char is a letter.
        }

        else {
            word[a] = counter; // Assign the array of index(a) to counter
            a++; // Go to the next index.
            counter = 0; // Reset the counter to create a new word.

        }

    }

    for (int j = 0; j < word.length; j++) { //Prints out all the arrays.
        System.out.println(word[j]); // Print the value of each array.

        }
    }
}

【问题讨论】:

  • 很可能你必须遍历字符串两次——第一次你会确定有多少单词。你可以通过计算非字母的数量来做到这一点。那么如果n是字数的话,可以根据需要创建new int[n]或者new String[n]。如果允许您使用ArrayList,那会更好,因为您不需要事先知道它有多大。但如果你必须使用数组,这将是一种方法。
  • 我还没有学过接口,所以还不会使用接口。但是我在运行程序时遇到了错误。这是为什么呢?
  • @Majestic 也许你应该告诉我们你遇到了什么错误来帮助你编写代码。
  • 这是第 24 行的“java.lang.ArrayIndexOutOfBoundsException: 0”,即 else 语句中“word[a] = counter”处的行。

标签: java arrays string for-loop string-length


【解决方案1】:

从代码来看,你得到的错误是当你试图用 a++ 递增 a 时。

word[a] = counter; // Assign the array of index(a) to counter
a++; // Go to the next index.

但是,您永远不会调整数组的大小。您不能简单地增加数组索引的值。这将在数​​组中查找尚不存在的索引。

import java.util.Scanner;

public class QnA {

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

        int[] word = new int[0]; // Creating an array.

        String string;
        System.out.print("Enter a String of Data Please: ");
        string = input.nextLine();

        // Close the scanner --
        input.close();

        //string = "What is 8this pro98gram doin8g?";

        int counter = 0;
        for (int i = 0; i < string.length(); i++) {
            //System.out.println("Test");
            // Check to see if charAt(i) is a letter.
            if (Character.isLetter(string.charAt(i))) {             
                // Counter every time the next char is a letter.
                counter++;
            } else {
                // Check if there are any valid characters
                if (counter > 0) {
                    // Resize the array and add the new char count
                    word = addToArray(word, counter);
                    // Reset the counter to create a new word.
                    counter = 0;
                }
            }
        }
        /* if the last characters in the string were letters then we need to
         * add the last count to the array
        */
        if (counter > 0) {
            // Resize the array and add the new char count
            word = addToArray(word, counter);
        }
        // Prints out all the arrays.
        for (int j = 0; j < word.length; j++) {
            // Print the value of each array.
            System.out.println(word[j]);
        }
    }

    public static int[] addToArray(int[] array, int charCount){
        // Resize the array
        array = resizeArray(array, array.length + 1);
        // Get the length and reduce 1 to get the last array index
        array[array.length - 1] = charCount;

        return array;
    }

    public static int[] resizeArray(int[] arrayToResize, int size) {
        // create a temp array
        int[] tempArray = new int[size];

        // check if the new size is different to the new size
        if (arrayToResize.length != size) {
            // copy array contents to new array
            for (int i = 0; i < arrayToResize.length; i++) {
                tempArray[i] = arrayToResize[i];
            }
        } else {
            tempArray = arrayToResize;
        }
        // return copied array resized.
        return tempArray;
    }
}

我已根据您的代码将其放在一起。您需要查看代码末尾的两个函数; addToArray 和 resizeArray。

这些负责将新计数添加到数组中,并将数组的大小调整为比原来更大的大小。

一种更优雅的方法是使用列表,因为您可以简单地添加下一个计数,而无需知道最终大小是多少。要了解有关列表的更多信息,请查看 JavaDocsTutorialsPoint 上的一个很好的示例。

【讨论】:

  • 谢谢大卫!这很有帮助!
猜你喜欢
  • 2017-04-16
  • 2011-11-08
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
相关资源
最近更新 更多