简体   繁体   English

用给定范围内用户的双精度数填充数组

[英]Filling an array with doubles from user in a given range

So it's time to come back to the users of stackoverflow for help again on an assignment.因此,是时候再次向 stackoverflow 的用户寻求帮助了。

I'm supposed to fill an array with a size of 10 with doubles given from the user.我应该用用户给出的双精度数填充一个大小为 10 的数组。 The entered numbers are supposed to be grades so they have to be in the range of 0 - 100. Anything out of the range (more, less, or incorrect characters) are not saved to the array and the user is prompted to try again at the given index of the array.输入的数字应该是等级,因此它们必须在 0 - 100 的范围内。超出范围的任何内容(更多、更少或不正确的字符)都不会保存到数组中,并且会提示用户重试数组的给定索引。 After either the array is filled to the max value or the user presses enter to skip, the program is supposed to return the grades entered in order and display the average.在数组填充到最大值或用户按回车键跳过后,程序应该按顺序返回输入的成绩并显示平均值。

public static final SIZE = 10;

Scanner userIn = new Scanner(System.in);
double[] grades = new double [SIZE];
int counter = 0;
int counterList = 1;
boolean exit = false;
String sTemp = "";
double gradeNum = 0;
double avrGrade = 0.0;
double sum = 0;

while((counter < SIZE) && (!exit)) {
    System.out.println("Enter grade " + counterList +
            ", or press enter to quit.");
    sTemp = userIn.nextLine();
    counterList++;
    if(sTemp.length() < 1) {
        exit = true; //ending for loop
    } else {
        gradeNum = Double.parseDouble(sTemp);
        grades[counter] = gradeNum;
        counter++;
    } //else statement
} //end of while loop
counterList = 1;
System.out.println("You entered " + counter + " grades total.");
for(int i = 0; i <= counter; i++) {
    System.out.println("Your grade " + counterList + " is " + grades[i]);
    counterList++;
}
for(int i = 0; i < grades.length; i++)
    sum += grades[i];
System.out.println("The average grade is: " + sum / grades.length);

So I finished taking my user's input and calculating the average but I'm having trouble setting the range and not saving the invalid inputs.因此,我完成了用户的输入并计算了平均值,但我无法设置范围并且没有保存无效输入。 I also feel like once I started to struggle I got really sloppy and there might be stuff going on in there that's not needed.我也觉得一旦我开始挣扎,我就会变得非常草率,并且可能会发生一些不需要的事情。 Let me know anything helps!让我知道有什么帮助!

An example of what the program should output given different scenarios output 给定不同场景的程序示例

You can trim down your code.你可以精简你的代码。 There are variables that you don't require.有些变量是您不需要的。 Explanations after the code.代码后的解释。

import java.util.Scanner;

public class GradeAvg {
    private static final int  SIZE = 10;

    public static void main(String[] args) {
        Scanner userIn = new Scanner(System.in);
        double[] grades = new double [SIZE];
        int counter = 0;
        String sTemp = "";
        double sum = 0;

        while(counter < SIZE) {
            System.out.println("Please enter grade " + (counter + 1) + ": ");
            sTemp = userIn.nextLine();
            if (sTemp.isEmpty()) {
                break;
            }
            try {
                grades[counter] = Double.parseDouble(sTemp);
            }
            catch (NumberFormatException xNumberFormat) {
                System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
                continue;
            }
            if (grades[counter] < 0  ||  grades[counter] > 100) {
                System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
                continue;
            }
            sum += grades[counter];
            counter++;
        } //end of while loop
        for (int i = 0; i < counter; i++) {
            System.out.println("grade " + (i + 1) + ": " + grades[i]);
        }
        System.out.println();
        System.out.println("number of valid grades entered: " + counter);
        System.out.println();
        System.out.println("average: " + sum / counter);
    }
}

After accepting the user input, first check if the user simply pressed <ENTER> without entering a value.接受用户输入后,首先检查用户是否在没有输入值的情况下直接按下<ENTER> I used method isEmpty() , of class java.lang.String , to do this check.我使用了 class java.lang.String的方法isEmpty()来做这个检查。 If the user simply pressed <ENTER> , you need to exit the while loop.如果用户只是按下<ENTER> ,则需要退出while循环。 This is what break does.这就是break的作用。 So no need for boolean variable exit .所以不需要boolean变量exit

Variable counter is all you need to both keep track of how many grades have been entered and which index of array grades needs to be assigned a value, so no need for variable counterList .变量counter是您只需要跟踪输入了多少成绩以及需要为数组grades的哪个索引分配值,因此不需要变量counterList

If an invalid value is entered, continue skips the rest of the while loop and starts a new loop iteration.如果输入了无效值,则continue跳过while循环的 rest 并开始新的循环迭代。 Think of it as a sort of goto that jumps back to the statement:将其视为一种跳转到语句的goto

while (counter < SIZE)

You can assign a value directly to an element in array grades so no need for variable gradeNum .您可以将值直接分配给数组grades中的元素,因此不需要变量gradeNum

You can update variable sum inside the while loop so no need for the extra for loop in order to calculate the average.您可以在while循环内更新变量sum ,因此不需要额外for循环来计算平均值。 By the way, your calculation of the average is incorrect since you are dividing by the size of array grades and not by the actual number of grades that were entered.顺便说一句,您对平均值的计算是不正确的,因为您除以数组grades的大小而不是输入的实际成绩数。 Adding up all the elements in array grades still gives you the correct sum since all elements of the array are implicitly initialized to 0 (zero).将数组grades中的所有元素相加仍然可以得到正确的sum ,因为数组的所有元素都被隐式初始化为 0(零)。

I changed what the program displays on the screen so as to match your example of what the program should output given different scenarios .我更改了程序在屏幕上显示的内容,以便与您的示例相匹配,在不同的场景下,程序应该是 output

Here is the output according to the sample you provided.根据您提供的样品,这是 output。

Please enter grade 1: 
A
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 1: 
100
Please enter grade 2: 
Bob
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 2: 
41.5
Please enter grade 3: 
-7
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 3: 

grade 1: 100.0
grade 2: 41.5

number of valid grades entered: 2

average: 70.75

I made some adjustments:我做了一些调整:

    final int SIZE = 10;
    Scanner userIn = new Scanner(System.in);
    double[] grades = new double [SIZE];
    int counter = 0;
    String sTemp = "";
    double gradeNum = 0;
    double sum = 0;
    
    while(counter < SIZE) {
        
        boolean err = false;
        System.out.println("Enter grade " + (counter + 1) +
                ", or press enter to quit.");
        sTemp = userIn.nextLine();
        
        try {
            gradeNum = Double.parseDouble(sTemp);
        } catch(NumberFormatException ex)
        { 
            err = true;
        }
        
        if(sTemp.length() < 1) {
            
            break; //ending the loop

            } else if(gradeNum <= 100 && gradeNum >= 0 && !err)
            {                   
                grades[counter] = gradeNum;
                counter++;
            } else
            {
                System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
            }
    } //end of while loop
    userIn.close(); //closing the Scanner
      
    System.out.println("You entered " + counter + " grades total.");
    for(int i = 0; i < counter; i++) {
        
        System.out.println("Your grade " + (i + 1)+ " is " + grades[i]);
    }
    
    for(int i = 0; i < counter; i++) {
        
        sum += grades[i];
        
    }

    System.out.println("\nNumber of valid grades entered: " + counter + "\n");
    
    System.out.println("The average grade is: " + sum / counter);
    
}

This seems to work, I made some corrections (like SIZE declaration, took out the println from the last loop, replaced exit with a break statement, ...).这似乎可行,我做了一些更正(如 SIZE 声明,从最后一个循环中取出 println,用 break 语句替换 exit,......)。 The most relevant changes are the input checks and the average grade calculation (I used counter instead of grades.length because it is always 10).最相关的变化是输入检查和平均成绩计算(我使用 counter 而不是 grades.length 因为它总是 10)。 The try/catch checks if the input string contains only numbers. try/catch 检查输入字符串是否只包含数字。

(sorry for bad english, just ask if something isn't clear) (抱歉英语不好,如果有什么不清楚的地方就问)

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

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