Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在中扫描值的简化方法?_Java - Fatal编程技术网

Java 在中扫描值的简化方法?

Java 在中扫描值的简化方法?,java,Java,当前我正在扫描4个考试分数等级,每个等级都有自己的变量,这些变量已经声明和初始化。我想知道是否有更好的方法来减少混乱。请容忍我,因为我目前在uni上我的第一堂java课,没有任何经验,所以我不希望这个解决方案是超级复杂的,至少现在还不是,但是一些容易理解的东西。不确定它是否有用/重要,但我正在使用BlueJ作为我的IDE import java.util.*; public class GradeCalculatorDriver { public static void main(St

当前我正在扫描4个考试分数等级,每个等级都有自己的变量,这些变量已经声明和初始化。我想知道是否有更好的方法来减少混乱。请容忍我,因为我目前在uni上我的第一堂java课,没有任何经验,所以我不希望这个解决方案是超级复杂的,至少现在还不是,但是一些容易理解的东西。不确定它是否有用/重要,但我正在使用BlueJ作为我的IDE

import java.util.*;

public class GradeCalculatorDriver
{
    public static void main(String [] args){
        String s1 = "student";//Declare student string variable;
        String s2;
        double exam1 = 0;//Declare and initalize variables.
        double exam2 = 0;//Declare and initalize variables.
        double exam3 = 0;//Declare and initalize variables.
        double exam4 = 0;//Declare and initalize variables.

        do{
            Scanner input = new Scanner(System.in);
            System.out.println("This program will calculate the average of 4 exam scores, and return the lowest, highest, and letter grade associated with the average");

            System.out.println("Please enter the name of the student");//Request student name and scans it into a string.
            String student = input.next();

            System.out.println("Please enter one exam score, then hit enter and repeat for following grades.");//Request exam scores and scan them into variables.
            exam1 = input.nextDouble();
            exam2 = input.nextDouble();
            exam3 = input.nextDouble();
            exam4 = input.nextDouble();

            double highest = GradeCalculator.high(exam1, exam2, exam3, exam4);//Calls highest grade method.
            double lowest = GradeCalculator.low(exam1, exam2, exam3, exam4);//Calls lowest grade method.
            double average = GradeCalculator.avg(exam1, exam2, exam3, exam4);//Calls average grade method.
            char letterGrade = GradeCalculator.letter(exam1, exam2, exam3, exam4);//Calls letter grade method.

            System.out.printf("The highest exam score is : %.2f " + highest);//Displays highest grade.
            System.out.printf("The lowest exam score is : %.2f " + lowest);//Displays lowest grade.
            System.out.printf("The average exam score is : %.2f " + average);//Displays average grade.
            System.out.print("The letter grade is " + letterGrade);//Displays letter grade associated with average.

            System.out.println("Would you like to enter another students grades? (yes/no)");//asks the user if they would like to calculate another factorial.
            s2 = input.next();

        } while (s2.equalsIgnoreCase("YES"));//checks to see what the users response was. 
        System.out.print("Thank you for using my program!");//Ending statement.
    }
}


public class GradeCalculator{

public static double high(double exam1, double exam2, double exam3, double exam4){//Calculates the highest exam score entered.
        double highest;//Declare and initilize variable.

        highest = Math.max(Math.max(Math.max(exam1, exam2), exam3), exam4);

        return highest;//Returns highest exam score.
    }

    public static double low(double exam1, double exam2, double exam3, double exam4){//Calculates the lowest exam score entered.
        double lowest = 0;//Declare and initilize variable.

        lowest = Math.min(Math.min(Math.min(exam1, exam2), exam3), exam4);

        return lowest;//Returns highest exam score.
    }

    public static double avg (double exam1, double exam2, double exam3, double exam4){//Calculates the average exam score.
        double average;//Declare variable.
        double count = 4;//Declare and initilize variable.

        average = ((exam1 + exam2 + exam3 + exam4) / count);

        return average;//Returns average grade.
    }


        public static char letter (double exam1, double exam2, double exam3, double exam4){//Calculates the letterGrade based on the average exam score.
            char letterGrade;//Declare and initilize variable.
            double count = 4;//Declare and initilize variable.
            double average = ((exam1 + exam2 + exam3 + exam4) / count);//declare and calculate average score.

            if (average >= 90)
                letterGrade = 'A';
            else if (average >= 80)
                letterGrade = 'B';
            else if (average >= 70)
                letterGrade = 'C';
            else if (average >= 60)
                letterGrade = 'D';
            else 
                letterGrade = 'E';

            return letterGrade;//Returns letter grade.
        }
    }

您可以使用
List scores=new ArrayList()
保存考试分数值并减少代码混乱。然后,当您从用户输入中添加新的考试分数时,您将为每个输入值调用
scores.add(input.nextDouble())

好吧,在我看来,如果这是你第一次踢猫(可以这么说),那么你很快就会成为一名成功的Java程序员。至于减少混乱,我想这取决于您已经学到了什么,比如已经介绍过的Java方法和语句,现在您可以自行创建一个应用程序来完成手头的任务。实际上,没有办法知道您的学习程度,因此下面提供的建议仅应定义为建议:

您当前的模型没有什么问题,只是出现了一些小错误,这些错误将生成MissingFormatArgumentException,并且在代码行中:

System.out.printf("The highest exam score is : %.2f " + highest);
System.out.printf("The lowest exam score is : %.2f " + lowest);
System.out.printf("The average exam score is : %.2f " + average);
应该首先修复代码中的任何错误。上面的每一行代码都包含一个错误,这仅仅是因为没有为格式说明符(.2f)提供参数。这是因为您在逗号分隔符的位置放置了加号(+)字符,以指示%.2f要表示的参数。在这种情况下,+会将以下字符串或变量内容附加到前面的字符串中。代码应为:

System.out.printf("The highest exam score is : %.2f ", highest);
System.out.printf("The lowest exam score is : %.2f ", lowest);
System.out.printf("The average exam score is : %.2f ", average);
或者只使用以下方法:

不应在do/while循环的每次迭代中声明扫描仪。将此声明置于do/while代码块上方,以免打开不必要的扫描仪实例

不需要在每次迭代do/while循环时解释应用程序功能。将此消息移到do/while代码块上方

提示用户输入时,除非您希望收到字符串标记,否则不要使用该方法。有时使用这种方法很简单。在我看来,我觉得它可以提供更多的灵活性,并允许您有更好的机会来防止可能的异常(如果您可以防止异常,请不要依赖异常)

信不信由你…有时注释可能是造成代码混乱的最大原因。绝对没有必要评论显而易见的事情。是的,我可能这样做了,但这只是为了解释代码。预计它将被删除

您可以去掉代码行:
strings1=“student”//声明学生字符串变量。您似乎没有在任何地方使用此变量

正如已经建议的那样,可以使用数组或收集机制来保存学生的分数,但是在减少混乱的意义上,它不会只保存4分,而是保存更多的分数,因此是处理这部分代码的一种好方法。无论如何,如果你的课程已经涵盖了数组和或数组列表的使用,那么这仍然是一个很好的方法。不确定您的需求是否仅利用您所学的知识。无论如何

要使用数组存储学生分数,您还需要修改成绩计算器类中的所有方法。这本身将消除参数混乱,因为每个方法只需要一个参数,而不是4个。如果要使用数组,该类中的方法可能如下所示:

public class GradeCalculator {
    public static double high(double[] exams) {//Calculates the highest exam score entered.
        double highest = 0.0d;//Declare and initilize variable to 0.0
        for (int i = 0; i < exams.length; i++) {
            if (exams[i] > highest) {
                highest = exams[i];
            }
        }
        return highest;//Returns highest exam score.
    }

    public static double low(double[] exams) {//Calculates the lowest exam score entered.
        double lowest = exams[0];
        for (int i = 0; i < exams.length; i++) {
            if (exams[i] < lowest) {
                lowest = exams[i];
            }
        }
        return lowest;//Returns lowest exam score.
    }

    public static double avg(double[] exams) {//Calculates the average exam score.
        double average = 0.0d;  //Declare variable.
        double sum = 0.0d;
        for (int i = 0; i < exams.length; i++) {
            sum+= exams[i];
        }
        average = sum / exams.length;
        return average; //Returns average grade.
    }

    //Calculates the letter-Grade based on the average exam score.
    public static char letter(double average) {
        char letterGrade;//Declare and initilize variable.
        if (average >= 90) {
            letterGrade = 'A';
        }
        else if (average >= 80) {
            letterGrade = 'B';
        }
        else if (average >= 70) {
            letterGrade = 'C';
        }
        else if (average >= 60) {
            letterGrade = 'D';
        }
        else {
            letterGrade = 'E';
        }
        return letterGrade; //Returns letter grade.
    }
}
此操作的代码可能如下所示:

String s2;
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; // Declare Array
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
            + LS + "desired exam scores and return the lowest,  highest, and "
            + LS + "letter grade associated with that determined average." + LS);

do {
    s2 = "";
    invalidEntry = false;
    // Request Student Name
    System.out.println("Please enter the name of the student (nothing to exit):");
    String student = input.nextLine();
    if (student.equals("")) { break; }

    // Request exam scores
    System.out.println("Please enter all student scores (each separated with a space): ");
    String scores = input.nextLine();
    // If nothing was supplied break out of loop 
    if (scores.equals("")) { 
        invalidEntry = true;
        break; 
    } 
    String[] scoresArray = scores.split("\\s+");  // Split the input into single scores (regex "\\s+" is used to split on one or more whitespaces).
    exams = new double[scoresArray.length]; // Initalize Array.
    // Convert scores to double data type...
    for (int i = 0; i < scoresArray.length; i++) {
        /* Is the string value actually a numerical signed
           or unsigned integer or double type value. Save
           this Regular Expression. It's handy to have.  */
        if (scoresArray[i].matches("-?\\d+(\\.\\d+)?")) {
            exams[i] = Double.parseDouble(scoresArray[i]);
        }
        else {
            System.out.println("One or more of the Scores supplied are invalid! "
                             + "Enter Student Scores again!" + LS);
            invalidEntry = true;
            break;
        }
    }
    if (invalidEntry) { continue; } // Redo loop on Invalid Entry

    double highest = high(exams);
    double lowest = low(exams);
    double average = avg(exams);
    char letterGrade = letter(average);

    System.out.println(LS + "Results For Student:       " + student); 
    System.out.println("From " + String.format("%02d" , exams.length) + 
                       " exam scores:       " + 
                       Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
    System.out.println("The lowest exam score is:  " + String.format("%.2f",lowest));
    System.out.println("The highest exam score is: " + String.format("%.2f", highest)); 
    System.out.println("The average exam score is: " + String.format("%.2f", average));
    System.out.println("The letter grade is:       " + letterGrade + LS);

    while (s2.equals("")) {
        System.out.println("Would you like to enter another Students Scores? (yes/no)");
        s2 = input.nextLine();
        if (!s2.equalsIgnoreCase("yes") && !s2.equalsIgnoreCase("no")) {
            System.out.println("Invalid Response! 'Yes' or 'No' only!");
            s2 = "";
        }
    }

} while (s2.equalsIgnoreCase("yes") || invalidEntry);
System.out.println("Thank you for using my program!");
String s2;
int indexCounter; // Declare an index counter for array.
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; //Declare Array.
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
            + LS + "desired exam scores and return the lowest,  highest, and "
            + LS + "letter grade associated with that determined average." + LS);

do {
    s2 = "";
    indexCounter = 0; // Set index counter to 0
    invalidEntry = false;

    // Request Student Name
    System.out.println("Please enter the name of the Student (nothing to exit):");
    String student = input.nextLine();
    if (student.equals("")) { break; }

    // Get number of Scores to enter from User
    int numberOfScores = 0;
    while (numberOfScores == 0) {
        System.out.println("Please enter the number of scores you wish to enter:");
        String numScores = input.nextLine();
        // Is the value supplied a String Integer value
        if (!numScores.matches("\\d+")) {
            System.out.println("Invalid number of scores provided! Try Again..." + LS);
            continue;
        }
        numberOfScores = Integer.parseInt(numScores);
    }
    exams = new double[numberOfScores]; // Initialize Array

    // Request exam scores
    while (indexCounter < numberOfScores) {
        System.out.println("Please enter exam score #" + (indexCounter + 1) + 
                " then hit enter: ");
        exams[indexCounter] = input.nextDouble();
        input.nextLine();  // Clear the scanner buffer
        indexCounter++;
    }

    double highest = high(exams);
    double lowest = low(exams);
    double average = avg(exams);
    char letterGrade = letter(average);

    System.out.println(LS + "Results For Student:       " + student);
    System.out.println("From " + String.format("%02d" , exams.length) + 
                       " exam scores:       " + 
                       Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
    System.out.println("The lowest exam score is:  " + String.format("%.2f",lowest));
    System.out.println("The highest exam score is: " + String.format("%.2f", highest)); 
    System.out.println("The average exam score is: " + String.format("%.2f", average));
    System.out.println("The letter grade is:       " + letterGrade + LS);

    while (s2.equals("")) {
        System.out.println("Would you like to enter another Student's Scores? (yes/no)");
        s2 = input.nextLine();
        if (!s2.equalsIgnoreCase("YES") && !s2.equalsIgnoreCase("NO")) {
            System.out.println("Invalid Response! 'Yes' or 'No' only!");
            s2 = "";
        }
    }
} while (s2.equalsIgnoreCase("YES") || invalidEntry);
System.out.println("Thank you for using my program!");
字符串s2;
布尔无效恒等式;
字符串LS=System.lineSeparator();
双重[]考试;//声明数组
扫描仪输入=新扫描仪(System.in);
System.out.println(“此程序将计算任意数量的
+LS+“期望的考试分数并返回最低、最高和”
+LS+“与确定的平均值相关的字母等级。”+LS);
做{
s2=“”;
无效=错误;
//请求学生姓名
System.out.println(“请输入学生姓名(无需退出):”;
字符串student=input.nextLine();
如果(student.equals(“”){break;}
//要求考试成绩
System.out.println(“请输入所有学生分数(每个分数用空格分隔):”;
字符串分数=input.nextLine();
//如果未提供任何内容,则断开循环
如果(分数等于(“”){
无效=正确;
打破
} 
String[]scoresArray=scores.split(\\s+);//将输入拆分为单个分数(regex“\\s+”用于拆分一个或多个空格)。
检查=新的双精度[scoresArray.length];//初始化数组。
//将分数转换为双精度数据类型。。。
for(int i=0;iString s2;
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; // Declare Array
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
            + LS + "desired exam scores and return the lowest,  highest, and "
            + LS + "letter grade associated with that determined average." + LS);

do {
    s2 = "";
    invalidEntry = false;
    // Request Student Name
    System.out.println("Please enter the name of the student (nothing to exit):");
    String student = input.nextLine();
    if (student.equals("")) { break; }

    // Request exam scores
    System.out.println("Please enter all student scores (each separated with a space): ");
    String scores = input.nextLine();
    // If nothing was supplied break out of loop 
    if (scores.equals("")) { 
        invalidEntry = true;
        break; 
    } 
    String[] scoresArray = scores.split("\\s+");  // Split the input into single scores (regex "\\s+" is used to split on one or more whitespaces).
    exams = new double[scoresArray.length]; // Initalize Array.
    // Convert scores to double data type...
    for (int i = 0; i < scoresArray.length; i++) {
        /* Is the string value actually a numerical signed
           or unsigned integer or double type value. Save
           this Regular Expression. It's handy to have.  */
        if (scoresArray[i].matches("-?\\d+(\\.\\d+)?")) {
            exams[i] = Double.parseDouble(scoresArray[i]);
        }
        else {
            System.out.println("One or more of the Scores supplied are invalid! "
                             + "Enter Student Scores again!" + LS);
            invalidEntry = true;
            break;
        }
    }
    if (invalidEntry) { continue; } // Redo loop on Invalid Entry

    double highest = high(exams);
    double lowest = low(exams);
    double average = avg(exams);
    char letterGrade = letter(average);

    System.out.println(LS + "Results For Student:       " + student); 
    System.out.println("From " + String.format("%02d" , exams.length) + 
                       " exam scores:       " + 
                       Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
    System.out.println("The lowest exam score is:  " + String.format("%.2f",lowest));
    System.out.println("The highest exam score is: " + String.format("%.2f", highest)); 
    System.out.println("The average exam score is: " + String.format("%.2f", average));
    System.out.println("The letter grade is:       " + letterGrade + LS);

    while (s2.equals("")) {
        System.out.println("Would you like to enter another Students Scores? (yes/no)");
        s2 = input.nextLine();
        if (!s2.equalsIgnoreCase("yes") && !s2.equalsIgnoreCase("no")) {
            System.out.println("Invalid Response! 'Yes' or 'No' only!");
            s2 = "";
        }
    }

} while (s2.equalsIgnoreCase("yes") || invalidEntry);
System.out.println("Thank you for using my program!");
String s2;
int indexCounter; // Declare an index counter for array.
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; //Declare Array.
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
            + LS + "desired exam scores and return the lowest,  highest, and "
            + LS + "letter grade associated with that determined average." + LS);

do {
    s2 = "";
    indexCounter = 0; // Set index counter to 0
    invalidEntry = false;

    // Request Student Name
    System.out.println("Please enter the name of the Student (nothing to exit):");
    String student = input.nextLine();
    if (student.equals("")) { break; }

    // Get number of Scores to enter from User
    int numberOfScores = 0;
    while (numberOfScores == 0) {
        System.out.println("Please enter the number of scores you wish to enter:");
        String numScores = input.nextLine();
        // Is the value supplied a String Integer value
        if (!numScores.matches("\\d+")) {
            System.out.println("Invalid number of scores provided! Try Again..." + LS);
            continue;
        }
        numberOfScores = Integer.parseInt(numScores);
    }
    exams = new double[numberOfScores]; // Initialize Array

    // Request exam scores
    while (indexCounter < numberOfScores) {
        System.out.println("Please enter exam score #" + (indexCounter + 1) + 
                " then hit enter: ");
        exams[indexCounter] = input.nextDouble();
        input.nextLine();  // Clear the scanner buffer
        indexCounter++;
    }

    double highest = high(exams);
    double lowest = low(exams);
    double average = avg(exams);
    char letterGrade = letter(average);

    System.out.println(LS + "Results For Student:       " + student);
    System.out.println("From " + String.format("%02d" , exams.length) + 
                       " exam scores:       " + 
                       Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
    System.out.println("The lowest exam score is:  " + String.format("%.2f",lowest));
    System.out.println("The highest exam score is: " + String.format("%.2f", highest)); 
    System.out.println("The average exam score is: " + String.format("%.2f", average));
    System.out.println("The letter grade is:       " + letterGrade + LS);

    while (s2.equals("")) {
        System.out.println("Would you like to enter another Student's Scores? (yes/no)");
        s2 = input.nextLine();
        if (!s2.equalsIgnoreCase("YES") && !s2.equalsIgnoreCase("NO")) {
            System.out.println("Invalid Response! 'Yes' or 'No' only!");
            s2 = "";
        }
    }
} while (s2.equalsIgnoreCase("YES") || invalidEntry);
System.out.println("Thank you for using my program!");