2015-10-14 63 views
0

我想知道如何让扫描仪可以在同一行上获取所有不同的号码。我的任务有要求我们计算年级平均值,他希望它是这样的:从同一行获取号码

输入等级的数量: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); 

} 
+0

'nextInt','next','nextDouble'等都查找同一行上的下一个标记,如果当前行中没有标记,只会查看下一行。 – RealSkeptic

回答

0

我想在你的作业分离的空间意味着你应该存储在特定位置或变量中的每个号码。

例如: 输入三个编号:1 2 3

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

现在扫描器将由nextInt()方法读出。如果它读取空间,那么将完成该变量的保存值。

另一示例读数组元素:

输入三个编号:1 2 3

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

。注意,循环运行的3倍的阵列的长度。 也请注意在代码中输入Scanner类的引用,但我没有声明它。

+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;