简体   繁体   English

输入一个数组的元素个数,将数组输入并显示数组的奇偶元素在其指定的arrays

[英]Take input of number of elements of an array, and input the array and display the odd and even elements of the array in their specified arrays

I have written the question I have to write the code for in the title but I am getting certain errors in my code.我已经在标题中写下了我必须为其编写代码的问题,但我的代码中出现了某些错误。
The errors are:错误是:
line 7: numOfVal cannot be resolved or is not a field第 7 行:numOfVal 无法解析或不是字段
line 23: numOfVal cannot be resolved to a variable第 23 行:numOfVal 无法解析为变量
line 25: cannot invoke add(int) on the array type int[]第 25 行:无法在数组类型 int[] 上调用 add(int)
line 28: cannot invoke add(int) on the array type int[]第 28 行:无法在数组类型 int[] 上调用 add(int)
line 47: oddarray cannot be resolved to a variable第 47 行:oddarray 无法解析为变量
line 48: evenarray cannot be resolved to a variable第 48 行:evenarray 无法解析为变量
I would be very grateful if you could help me fix the errors in my code.如果您能帮助我修复代码中的错误,我将不胜感激。
Thanks.谢谢。

import java.util.Scanner;

public class CountEvenOddArray {
    int[] mainarray;
    void setInpLength(int numOfVal) {
        this.numOfVal = numOfVal;
    }
    void setVal(int index,
            int Val) {
        this.mainarray[index] = Val;
    }
    
    void MainArrays() {
        mainarray = new int[100];
    }
    
    
    void EvenOdds() {
        
        int evenarray[] = new int[100];
        int oddarray[] = new int[100];
        for (int i = 0; i <numOfVal ; i++ ) {
            if (mainarray[i]%2 == 0) {
                evenarray = evenarray.add(mainarray[i]);
            }
            else {
                oddarray = oddarray.add(mainarray[i]);
            }
        }
    }
    public static void main(String[] args) {
        CountEvenOddArray abc = new CountEvenOddArray();
        int numOfVal;
        int mainarray[]  = new int[100];
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of elements you want to store:");
        numOfVal = sc.nextInt();
        abc.setInpLength(numOfVal);
        
        System.out.println("Enter the elements of the array: ");
        for (int k = 0; k < numOfVal; k++ ) {
            abc.setVal(k, sc.nextInt());
        }
        abc.EvenOdds();
        sc.close();
        System.out.println("The array with the odd elements is:" + oddarray);
        System.out.println("The array with the even elements is:" + evenarray);
    }
}  ```

Here is a runnable example of how this task could be accomplished.这是一个如何完成此任务的可运行示例。 You will notice that there are very few methods required.您会注意到只需要很少的方法。 Having too many methods to carry out single simple tasks that can be accomplished with single lines of code just makes things harder to follow and bloats the application.有太多的方法来执行可以用单行代码完成的单一简单任务只会让事情更难遵循并使应用程序膨胀。 Be sure to read the comments within the code:请务必阅读代码中的注释:

import java.util.Scanner;

public class CountEvenOddArray {
    
    // Class member variables:
    private final String LS = System.lineSeparator();
    private int[] mainArray; 

    // Startup main() method (Application entry point):
    public static void main(String[] args) {
        // App started this way to avoid the need for statics:
        new CountEvenOddArray().startApp(args);
    }
    
    private void startApp(String[] args) {
        /* Open a keyboard input stream. You only ever need one 
           of these in any console application. Do not close this 
           stream unless you know for sure that you will never need 
           it again during your application session otherwise, you 
           will need to restart the application to use it again.
           The JVM will automatically close this resource when the 
           application ends.                       */
        Scanner sc = new Scanner(System.in);
        
        // Get the desired size of Main Array from User:
        String numOfElems = "";
        while(numOfElems.isEmpty()) {        
            System.out.println("Enter number of elements you want to store or");
            System.out.print(  "enter 'q' to quit: -> ");
            numOfElems = sc.nextLine().trim();
            // Is Quit desired?
            if (numOfElems.equalsIgnoreCase("q")) {
                // Yes....
                System.out.println("Quiting - Bye Bye");
                return; // Will force a return to main() and effectively end application.
            }
            // Entry Validation...
            /* If the entry does not match a string representation of a
               integer value. (See the isInteger() method below): */
            if (!isInteger(numOfElems)) {
                // Then inform the User and let him/her try again...
                System.out.println("Invalid Entry! (" + numOfElems + ") Try again..." + LS);
                numOfElems = ""; // Empty variable to ensure re-loop.
            }
        }
        
        // If we made it the far, then the entry is valid!
        // Convert the string input value to integer:
        int numOfElements = Integer.parseInt(numOfElems);
        
        // Initialize mainArray{}:
        mainArray = new int[numOfElements];
        
        // Have User enter the elements for the Array (with validation):
        System.out.println();
        System.out.println("Enter the elements of the array ('q' to quit):");
        for (int i = 0; i < numOfElements; i++ ) {
            // Prompt for each required mainArray[] Element:
            String elem = "";
            while (elem.isEmpty()) {
                System.out.print("Enter Element #" + (i+1) + ": -> ");
                elem = sc.nextLine().trim();
                // Is Quit desired?
                if (elem.equalsIgnoreCase("q")) {
                    // Yes....
                    System.out.println("Quiting - Bye Bye");
                    return; // Will force a return to main() and effectively end application.
                }
                // Entry Validation...
                /* If the entry does not match a string representation of a
                   integer value. (See the isInteger() method below): */
                if (!isInteger(elem)) {
                    // Then inform the User and let him/her try again...
                    System.out.println("Invalid Entry! (" + elem + ") Try again..." + LS);
                    elem = ""; // Empty variable to ensure re-loop.
                }
            }
            
            // If we made it the far, then the entry is valid!
            // Convert the string input value to integer element:
            int element = Integer.parseInt(elem);
            mainArray[i] = element;
        }
        
        /* mainArray[] is now initialized and filled. We will now create 
           the oddArray[] and evenArray[] from what is in the mainArray[]
           but, because we have no idea what the User may have entered 
           for element values, there is no real viable way to create exact
           fixed length int[] odd or even arrays unless we count them first. 
           This would require additional iterations basically meaning, we 
           are doing the job twice. We can get around this by placing our 
           odd/even results into a couple of List<Integer> Lists (which can 
           grow dynamically) then converting them to array later (if desired):  */
        java.util.List<Integer> odd = new java.util.ArrayList<>();
        java.util.List<Integer> even = new java.util.ArrayList<>();
        
        /* Determine Odd or Even value elements within the mainArray[]
           and place those values into the appropriate odd or even Lists.     */
        evenOdds(odd, even);
        
        // Convert Lists to int[] Arrays....
        // Convert List<Integer> odd to oddArray[]:
        int[] oddArray = odd.stream().mapToInt(d -> d).toArray();
        
        // Convert List<Integer> even to evenArray[]:
        int[] evenArray = even.stream().mapToInt(d -> d).toArray();
        
        // Display the oddArray[] and the evenArray[]...
        System.out.println();
        System.out.println(oddArray.length + " odd elements are in the oddArray[]:   -> " 
                            + java.util.Arrays.toString(oddArray));
        System.out.println(evenArray.length + " even elements are in the evenArray[]: -> " 
                            + java.util.Arrays.toString(evenArray));
    }
    
    /* Method to determine Odd or Even value elements within the mainArray[]
       and place those values into the appropriate odd or even Lists. The
       Lists are added to by way of reference to them therefore no returnable
       objects are required.   
    */
    private void evenOdds(java.util.List<Integer> odd, java.util.List<Integer> even ) {
        for (int i = 0; i < mainArray.length ; i++ ) {
            if (mainArray[i] % 2 == 0) {
                even.add(mainArray[i]);
            }
            else {
                odd.add(mainArray[i]);
            }
        }
    }
    
    public boolean isInteger(String value) {
        boolean result = true; // Assume true:
        // Is value null or empty?
        if (value == null || value.trim().isEmpty()) {
            result = false;
        }
        /* Is value a match to a string representation of 
           a integer value?        */
        else if (!value.matches("\\d+")) {
            result = false;
        }
        // Does value actually fall within the relm of an `int` data type?
        else {
            long lng = Long.parseLong(value);
            if (lng > Integer.MAX_VALUE || lng < Integer.MIN_VALUE) {
                result = false;
            }
        }
        return result;
    }
}

If run and your entries are like this within the Console Window:如果运行并且您的条目在控制台 Window 中如下所示:

Enter number of elements you want to store or
enter 'q' to quit: -> 5

Enter the elements of the array ('q' to quit):
Enter Element #1: -> 1
Enter Element #2: -> 3
Enter Element #3: -> 2
Enter Element #4: -> 5
Enter Element #5: -> 4

You should see something like this:你应该看到这样的东西:

3 odd elements are in the oddArray[]:   -> [1, 3, 5]
2 even elements are in the evenArray[]: -> [2, 4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM