Add a loop to verify input. Repeat the prompt if the input is zero or a negative
ID: 3589084 • Letter: A
Question
Add a loop to verify input. Repeat the prompt if the input is zero or a negative value. A second loop is needed to allow the program to repeat when “yes” is entered ignoring the case. Shown below is an example of the program executing.
Here is what I have so far
public class LabAssign5 {
public static void main(String[] args) {
// TODO code application logic here
long numSeconds;
String numOfSecondsString;
while (true) {
numOfSecondsString = JOptionPane.showInputDialog("Enter the Number of Seconds:");
numSeconds = Integer.parseInt(numOfSecondsString);
}
JOptionPane.showMessageDialog(null, "You eneterd " + numSeconds + " seconds ");
long numOfDays;
long remainingDays, numOfHours, remainingHours, numOfMinutes;
numOfDays = numSeconds / 84600;
remainingDays = numSeconds % 84600;
numOfHours = remainingDays/3600;
remainingHours = remainingDays % 3600;
numOfMinutes = remainingHours/60;
JOptionPane.showMessageDialog(null, "Days = " + numOfDays + " Hours = " + numOfHours + " Minutes = " + numOfMinutes + " Seconds = " + numSeconds );
}
}
Explanation / Answer
Here is the code:
import javax.swing.JOptionPane;
public class TestApp {
public static void main(String[] args) {
TestApp testAppObj = new TestApp();
testAppObj.convertSecondsToDays();
}
public void convertSecondsToDays()
{
// TODO code application logic here
long numSeconds = 0;
String numOfSecondsString,continueOrNot;
while (numSeconds <= 0) { // Run loop until a valid value entered.
numOfSecondsString = JOptionPane.showInputDialog("Enter number of seconds: ");
numSeconds = Integer.parseInt(numOfSecondsString);
}
JOptionPane.showMessageDialog(null, "You eneterd " + numSeconds + " seconds ");
long numOfDays;
long remainingDays, numOfHours, remainingHours, numOfMinutes;
numOfDays = numSeconds / 84600;
remainingDays = numSeconds % 84600;
numOfHours = remainingDays/3600;
remainingHours = remainingDays % 3600;
numOfMinutes = remainingHours/60;
JOptionPane.showMessageDialog(null, "Days = " + numOfDays + " Hours = " + numOfHours + " Minutes = " + numOfMinutes + " Seconds = " + numSeconds );
continueOrNot = JOptionPane.showInputDialog("If you want to continue, type "yes": ");
if(continueOrNot.equalsIgnoreCase("yes")) // loop for continuation
{
convertSecondsToDays();
}
else
{
return;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.