How can I allow for three integers to be entered followed by a space and a word before the system checks for exceptions?

StackOverflow https://stackoverflow.com/questions/21912891

Question

This is a homework assignment and I apologize for the dumb question I just can't seem to crack it and I have tried a few ways, including .hasInt();. The code I have works for checking if the user is entering integers buy won't allow anything after I want to allow the user to enter "5 hours, 10 minutes, 15 seconds.". So far I can only allow them to enter "5 10 15" and anything else gets caught by the exception and asks him to enter valid numbers. Here is the code.

import java.util.*;

public class TimetoSeconds
{
public static void main(String[] args)
{
    System.out.println("Time converter");
    System.out.println();
    //start scanner and variables
    Scanner sc = new Scanner(System.in);
    int x = 60;
    String choice = "y";
    while (choice.equalsIgnoreCase("y"))
    {
        //catch exceptions
        int hours = 0;
        int minutes = 0;
        int seconds = 0;
        try
        {
        // get user input
        System.out.print("Enter time in hours (space), minutes (space), and
                    seconds:  ");
        hours = sc.nextInt();
        minutes = sc.nextInt();
        seconds = sc.nextInt();
        System.out.println();
        }
        catch (InputMismatchException e)
        {
            sc.nextLine();
            System.out.print("Error! Invalid number. Try again.\n");
            continue;
        }

        int sec1 = (hours * x) * x;
        int sec2 = minutes * x;
        int totalSec = sec1 + sec2 + seconds;

        System.out.print("Total seconds are:  " + totalSec + "\n");
        System.out.println();

        System.out.print("Continue? (y/n):   ");
        choice = sc.next();
        System.out.println();
    }
}
}
Was it helpful?

Solution

Just change this part.

    System.out.print("Enter time in hours (space), minutes (space), and seconds:  ");
    hours = sc.nextInt();
    sc.next();
    minutes = sc.nextInt();
    sc.next();
    seconds = sc.nextInt();
    sc.next();

Then your program works OK.

Time converter

Enter time in hours (space), minutes (space), and seconds:  5 hours, 10 minutes, 12 seconds

Total seconds are:  18612

Continue? (y/n):   y

Enter time in hours (space), minutes (space), and seconds:  3 hours, 10 minutes, 20 seconds

Total seconds are:  11420

Continue? (y/n):   n

But this is kind of error-prone. I would rather read the whole big string
which the user enters e.g. "5 hours, 10 minutes, 20 seconds" and then
extract whatever I need from there (and I would need just the 3 numbers).
What is it error-prone? Because if the user types "5 hours , 10 minutes , 20 seconds",
it will still detect this as invalid input (as the commas are not glued to the words).

OTHER TIPS

You could read in the entire string using nextLine and then get the numbers with split:

    System.out.print("Enter time in hours (space), minutes (space), and seconds:  "); 
    String line = sc.nextLine();
    String values[] = line.trim().split("[^0-9]+");

The argument to split is a regular expression; it treats any sequence of one or more non-digits as a delimiter, and returns the substrings between the delimiters. Thus, all elements of values[] will be strings with just digits (except that values[0] could be an empty string), and you can use Integer.parseInt to get the actual integers. You can also easily check to make sure they've entered the correct number of integers. trim() just gets rid of leading and trailing spaces, so that if they enter " 5 10 15", it will still work. (But if they enter " give me 5, 10, 15", values[0] will be "", and values[1] will be "5", etc.) This solution won't let the user enter numbers on separate lines, the way using Scanner's nextInt would. If the ability to enter on separate lines is necessary, the above solution won't work without using a loop and some extra logic.

Maybe using StringTokenizer. Here is the link to the stringtokenizer in the java api.

It allows you to define the delimiters and get the substrings that these delimiters split.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top