-
Loop problems
I am attempting to write the following program, but running into problems and would like some advice.
Code:
/* TwoHighestScores.java
* Jim
* 10/17/2010
* This program prompts the user to enter the number oif students and each
students name and score, and finally displays the student with the highest
and the student with the second highest score */
import java.util.Scanner;
public class TwoHighestScores {
public static void main(String [] args) {
//Declare scanner variable for iput
Scanner input = new Scanner(System.in);
//Declare int variable for the number of students
final int NUMBER_OF_STUDENTS = 3;
//Declare string variable for student name
String studentName;
//Declare double variable for student score
double studentScore;
//Declare int variable for count
int count = 0;
System.out.println("This program finds the two highest scores" + "\n ");
//Create while loop to repeat 3 times
while( count < NUMBER_OF_STUDENTS ) {
//allow input for student name
studentName = input.nextLine();
//output to console
System.out.println("Enter Student Name");
//allow input for student score
studentScore = input.nextDouble();
//output to console
System.out.println("Enter Student Score");
count++;
}
}
}
I'm having two problems that I do not know how to resolve. The first is that when I run the program, it comes up to "This program finds the two highest scores" and then stops. It will not ask "Enter Student Name" until I hit enter.
I want it to show the first sentence then drop to a new line and ask to enter the student name. I thought adding the \n would help but it didn't.
The second problem is that after I enter a name and hit enter I get the following error:
Code:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at TwoHighScores.main(TwoHighestScores.java:31
-
Code:
while( count < NUMBER_OF_STUDENTS ) {
//allow input for student name
studentName = input.nextLine();
//output to console
System.out.println("Enter Student Name");
//allow input for student score
studentScore = input.nextDouble();
//output to console
System.out.println("Enter Student Score");
count++;
}
You ask for input first, then output "Enter student name", same for the score. Just reverse the order.
-
I've been banging my head against the monitor for an hour and couldn't see it until you pointed it out. arrrhgggh.
Thank you very much.
-
No probs, it's always the little things that slip by and give us grey hairs.