So I am working on a program to allow a user to add students to the class as well as manage their grades and what not. When a user selects the first option in the menu, he has to input an id (mandatory) but he could add a numerical score and/or a letter grade as well. Based on feedback in another post I managed to create a String variable line that reads user input, then checks whether it is "S"/"s" (to skip or not) and parses the value into double accordingly. Now building on the question, how can I skip the prompt and proceed to the next prompt if the user decides to skip adding a score? I have tried to use break; but it exits the entire loop . Is there a way to skip the question for score and proceed to the question for letter grade?
Output:
1) Add Students to Class
2) Remove a Student from Class
3) Set Grades for a Student
4) Edit Grades for a Student
5) Show Class Report
6) Exit
1
Kindly input id: Kindly input Score: (Enter s to Skip)
Kindly input Grade: (Enter s to Skip)
Code
// Prompting the user for Score (Numerical Grade)
System.out.println("Kindly input Score: (Enter s to Skip)");
// reading the input into the line variable of string datatype
String line = input.nextLine();
// checking if line =="s" or =="S" to skip, otherwise
// the value is parsed into a double
if("s".equals(line) || "S".equals(line))
{
break; // this exists the loop. How can I just skip this requirement
//and go to the next prompt?
}else try
{
score = Double.parseDouble(line);
System.out.println(score);
} catch( NumberFormatException nfe)
{
}
// Prompting the user for Numerical Grade
System.out.println("Kindly input Grade: (Enter s to Skip)");
String line2 = input.nextLine();
if("s".equals(line2) || "S".equals(line2))
{
break; // this exists the loop. How can I just skip this
// requirement and go to the next prompt?
}else try
{
score = Double.parseDouble(line2);
System.out.println(score);
} catch( NumberFormatException nfe)
{
}
Just remove the break
:
if("s".equals(line) || "S".equals(line))
{
// Don't need anything here.
}else {
try
{
score = Double.parseDouble(line);
System.out.println(score);
} catch( NumberFormatException nfe)
{
}
}
But it is better not to have an empty true
case (or, rather, it is unnecessary):
if (!"s".equals(line) && !"S".equals(line)) {
try {
// ...
} catch (NumberFormatException nfe) {}
}
You can also use String.equalsIgnoreCase
to avoid needing to test "s"
and "S"
.