从同一行获取号码

时间:2015-10-14 19:41:00

标签: java arrays loops

我想知道扫描仪如何能够在同一条线上拾取所有不同的数字。我的任务要求我们计算成绩平均值,他希望它像:

  

输入成绩数:5

     

输入5个等级:95.6 98.25 89.5 90.75 91.56

     

成绩的平均值为93.13

我认为扫描仪要获得这些数字需要一个数组吗?但我们还没有学到这些。任何帮助都是极好的!到目前为止,我有:

// number of grades input
    do {
        System.out.println("Enter number of grades");
        // read user input and assign it to variable
        if (input.hasNextInt()) {
            numGrade = input.nextInt();
            // if user enters a negative grade will loop again
            if (numGrade <= 0) {
                System.out.println("Your number of grades needs to positive! Try again");
                continue;
                // if grade number > 0 set loop to false and continue
            } else {
                cont = false;

            }
            // if user does not enter a number will loop again
        } else {
            System.out.println("You did not enter a number! Try again");
            // get the next input
            input.next();
            continue;
        }
        // only not loop when boolean is false
    } while (cont);
    // user input of grades
    do {
        // prompt user to enter the grades
        System.out.println("Enter the " + numGrade + " grades");
        // assign to input
        if (input.hasNextDouble()) {
            grades = input.nextDouble();
            // check if a grade is a negative number
            if (grades <= 0) {
                // report error to user and loop
                System.out.println("Your grades needs to positive! Try again");
                continue;
                // if user enter acceptable grades then break loop
            } else {
                cont2 = false;
            }
            // check if user entered a number
        } else {
            // if user did not enter number report error
            System.out.println("You did not enter a number! Try again");
            input.next();
            continue;
        }
        // only not loop when boolean2 is false
    } while (cont2);

    // average calculation
    average = grades / numGrade;
    System.out.println(average);

}

2 个答案:

答案 0 :(得分:3)

我会建议这个

// separates the line you send by spaces if you send the next line
// 95.6 98.25 89.5 90.75 91.56 it will create an array like this
// {"95.6","98.25", "89.5","90.75", "91.56"} 
String []grades = input.nextLine().split(' ');
double total=0;
for(int i=0;i<grades.length;i++){
  //parse each value to double and adds it to total
  total+=Double.parseDouble(grades[i]);

}
double average= total/grades.length;

答案 1 :(得分:0)

我认为在您的作业中,单独的空格意味着您应该将每个数字存储在特定的位置或变量中。

例如: 输入三个数字:1 2 3

int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();

现在Scanner将通过nextInt()方法读取。如果它读取空间,那么将完成在该变量中保存值。

读取数组元素的另一个示例:

输入三个数字:1 2 3

int[] myArray = new int[3];
for(int i = 0; i < myArray.length; i++){
   myArray[i] = input.nextInt();
}

请注意,循环将以数组长度运行3次。 另请注意在代码中输入Scanner类的引用,但我没有声明它。