简体   繁体   English

将用户输入多次存储在数组中

[英]Store user input in array multiple times

I'm working on a project which... 我正在做一个项目...

Allows the user to input 4 numbers that are then stored in an array for later use. 允许用户输入4个数字,然后将其存储在数组中以备后用。 I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values. 我还希望每次用户决定继续执行该程序时,它都会创建一个新的数组,可以将其与以后进行比较以获得最高的平均值,最高值和最低值。

The code is not done and I know there are some things that still need some work. 代码没有完成,我知道有些事情仍然需要做一些工作。 I just provided the whole code for reference. 我只是提供了完整的代码以供参考。

I'm just looking for some direction on the arrays part. 我只是在数组部分寻找方向。

*I believe I am supposed to be using a 2-D array but I'm confused on where to start. *我相信我应该使用2-D数组,但是我对从哪里开始感到困惑。 If I need to explain more please let me know. 如果需要更多说明,请告诉我。 (I included as many comments in my code just in case.) (以防万一,我在代码中包含了许多注释。)

I tried converting the inputDigit(); 我尝试转换inputDigit(); method to accept a 2-D array but can't figure it out. 接受二维数组但无法弄清楚的方法。

If this question has been answered before please redirect me to the appropriate link. 如果之前已经回答了这个问题,请重定向到相应的链接。

Thank you! 谢谢!

package littleproject;

import java.util.InputMismatchException;
import java.util.Scanner;

public class littleProject {

public static void main(String[] args) {
    // Scanner designed to take user input
    Scanner input = new Scanner(System.in);
    // yesOrNo String keeps while loop running
    String yesOrNo = "y";
    while (yesOrNo.equalsIgnoreCase("y")) {

        double[][] arrayStorage = inputDigit(input, "Enter a number: ");

        System.out.println();

        displayCurrentCycle();
        System.out.println();

        yesOrNo = askToContinue(input);
        System.out.println();

        displayAll();
        System.out.println();

            if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
                System.out.println("You have exited the program."
                    + " \nThank you for your time.");
            }
        }
    }

// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
    // Creates a 4 spaced array
    double array[][] = new double[arrayNum][4];

    for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
        // For loop that stores each input by user
        for (int counter = 0; counter < array.length; counter++) {
            System.out.print(prompt);

            // Try/catch that executes max and min restriction and catches
            // a InputMismatchException while returning the array
            try {
                array[counter] = input.nextDouble();
                if (array[counter] <= 1000){
                    System.out.println("Next...");
                } else if (array[counter] >= -100){
                    System.out.println("Next...");
                } else {
                    System.out.println("Error!\nEnter a number greater or equal to -100 and"
                            + "less or equal to 1000.");
                }
            } catch (InputMismatchException e){
                System.out.println("Error! Please enter a digit.");
                counter--; // This is designed to backup the counter so the correct variable can be input into the array
                input.next();
            }
        }
    }
return array;
}

// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
    int averageValue = 23; // Filler Variables to make sure code was printing
    int highestValue = 23;
    int lowestValue = 23;
    System.out.println(\n--------------------------------"
            + "\nAverage - " + averageValue 
            + "\nHighest - " + highestValue
            + "\nLowest - " + lowestValue);
}

public static void displayAll() {
    int fullAverageValue = 12; // Filler Variables to make sure code was printing
    int fullHighestValue = 12;
    int fullLowestValue = 12;
    System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
            + "\n--------------------------------"
            + "\nAverage Value - " + fullAverageValue
            + "\nHighest Value - " + fullHighestValue
            + "\nLowest Value - " + fullLowestValue);
}

// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
    boolean loop = true;
    String choice;
    System.out.print("Continue? (y/n): ");
    do {
        choice = input.next();
        if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
            System.out.println();
            System.out.println("Final results are listed below.");
            loop = false;
        } else {
            System.out.print("Please type 'Y' or 'N': ");
        }
    } while (loop);
    return choice;
}
}

As far as is understood, your program asks the user to input four digits. 据了解,您的程序要求用户输入四个数字。 This process may repeat and you want to have access to all entered numbers. 此过程可能会重复,您想访问所有输入的号码。 You're just asking how you may store these. 您只是在问如何存储这些内容。

I would store each set of entered numbers as an array of size four. 我会将每组输入的数字存储为大小为4的数组。
Each of those arrays is then added to one list of arrays. 然后将这些数组中的每一个添加到一个数组列表中。

A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays. 与二维数组相比,数组列表提供了动态添加新数组的灵活性。

We store the digits that the user inputs in array of size 4: 我们将用户输入的数字存储在大小为4的数组中:

public double[] askForFourDigits() {
    double[] userInput = new double[4];
    for (int i = 0; i < userInput.length; i++) {
        userInput[i] = /* ask the user for a digit*/;
    }
    return userInput;
}

You'll add all each of these arrays to one list of arrays: 您将所有这些数组都添加到一个数组列表中:

public static void main(String[] args) {
    // We will add all user inputs (repesented as array of size 4) to this list.
    List<double[]> allNumbers = new ArrayList<>();

    do {
        double[] numbers = askForFourDigits();
        allNumbers.add(numbers);

        displayCurrentCycle(numbers);
        displayAll(allNumbers);
    } while(/* hey user, do you want to continue */);
}

You can now use the list to compute statistics for numbers entered during all cycles: 现在,您可以使用该列表来计算所有周期中输入的数字的统计信息:

public static void displayAll(List<double[]> allNumbers) {
    int maximum = 0;
    for (double[] numbers : allNumbers) {
        for (double number : numbers) {
            maximum = Math.max(maximum, number);
        }
    }
    System.out.println("The greatest ever entered number is " + maximum);
}

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

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