|
-
December 1st, 2009, 10:37 PM
#1
problem involving arrays, search and sort
Hello I'm working on this problem
Enrolment in a class is limited to 50 students. For each student, name and a test score is given. Perform the following operations:
* Input student name and score for each student.
* Compute and output the class average.
* Output the name of each student whose score is below the average.
* Compute and output the highest score and the name of each student with the highest score.
* Input a student's name. If the student is in the course, output the test score; otherwise, output an appropriate message.
* Sort the data into alphabetical order by student name and output the sorted list, with student name and score.
for the input part would I use separate arrays for the names and scores? As for the other parts which sort and search algorithms should I use?
-
December 1st, 2009, 11:02 PM
#2
Re: problem involving arrays, search and sort
package assignment6;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String [] nameList = new String [50];
double [] scoreList = new double [50];
String name;
double score;
for (int i = 0; i < 5; i++){
System.out.println("Enter name for record number "+ (i+1));
name = in.nextLine();
nameList[i] = name;
System.out.println("Enter grade for record number "+ (i+1));
score = in.nextDouble();
scoreList[i] = score;
}
}
}
it works for the first iteration but for the 2nd one it just prints both out statements simultaneously and then asks for input. What should I do
Last edited by CodeMelon; December 2nd, 2009 at 12:29 AM.
-
December 2nd, 2009, 05:00 AM
#3
Re: problem involving arrays, search and sort
Calling nextDouble() returns the next double value from the Scanner's input stream. In the process it removes it from the stream so the next call to one of the hasXXX or nextXXX will act on any remaining values in the stream or the call will block until the stream has some value.
The problem you are seeing is because when the user types a number and presses the <ENTER> key the stream contains the number and a carriage return. The call to getDouble() removes the number but not the carriage return. The next scanner call (which is the next iteration of the loop) is nextLine() which immediately returns because the input stream still contains the carraige return. So your code drops straight through to the next print statement and the next scanner call which waits for a double to be entered as the input stream is now empty.
The solution is to put a call to nextLine() after your call to nextDouble() and just ignore the returned value.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|