Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

input time and compare to get max time entered

Status
Not open for further replies.

Lhuffst

Programmer
Jun 23, 2003
503
US
I am very new to Java and need to allow a user to enter a times (HH:MM format) and a rates until you enter stop. The output is to show the max and min rates and times.

I can get the rates but have problems with the times. If I make the times a String, then I can't get the compare to work. I tried to use the .useDelimiter to make it an int so the compare would work but get an error on that as well. I am hoping someone can tell me what I did wrong.

Code:
import java.util.*;

public class MaxTest
{
 public static void main(String[] args)
 {
 	//declare and initalize variables
	int pulseRate = 0, maxPulseRate= 0, minPulseRate=0,maxHours=0,maxMinutes=0;
	int maxTime= 0, minTime=0;
	
  	 Scanner input = new Scanner(System.in);
  
    System.out.print("Enter Patient Pulse Rate OR -1 to Stop: ");
	 pulseRate = input.nextInt();
	 
	 input.useDelimiter("[:\n]");
	 System.out.print("Enter Hours and Minutes (HH:MM) Pulse Was Taken: ");
	 int hours = input.nextInt();
	 int minutes = input.nextInt();
	 
 	int testTime = hours + minutes;
	System.out.print(testTime);

 while (pulseRate != -1) 
  {
  	 
		//get the max and min pulse rates
	 	if (pulseRate > maxPulseRate)
		{
			maxPulseRate= maxRate(pulseRate,maxPulseRate);
			maxTime = testTime;
			System.out.print("maxtime: " + maxTime);
		}	
				// if (pulseTime > maxTime)
// 				  {
// 				  	maxTime = testTime;
// 						System.out.print("pulse>: " + maxTime);
// 
// 						maxTime=pulseTime;
// 					}
// 				else
// 					{
// 							System.out.print("pulse <: " + maxTime);
// 						maxTime = maxTime;
// 					}
// 			 }
			else if (pulseRate < maxPulseRate)
			 {
						minPulseRate= minRate(pulseRate,minPulseRate);			 
						minTime =testTime;
			 };
			
			
					System.out.print("time = " + maxTime);
	
	 System.out.print("Enter Patient Pulse Rate OR -1 to Stop: ");
	 pulseRate = input.nextInt();
	 
	 if (pulseRate == -1)// exit the loop if -1 is entered
	    break;
		
	   System.out.print("Enter Hours and Minutes (HH:MM) Pulse Was Taken: ");
	  hours = input.nextInt();
	  minutes = input.nextInt();


 }  //end of while	
 System.out.print(" The max pulse Rate is:  " + maxPulseRate + maxTime + "\n ");
  System.out.print(" The min pulse Rate is:  " + minPulseRate  + minTime + "\n ");


 } //end of main
 
 //return the max pulse rate between 2 numbers
 public static int maxRate(int num1, int num2)
 {
  int result;
   System.out.print("CK MaxRate:\n " + num1 + " " + num2);
   
	if (num1 > num2)
	  result = num1;
	  
	else
		result= num2;
	
	return result;
} //end of maxRate

 //return the MIN pulse rate between 2 numbers
 public static int minRate(int num1, int num2)
 {
  int result;
   System.out.print("CK MINRate:\n " + num1 + " " + num2);
  if (num2 == 0)	//should be this the first time in
  		result = num1;
  else if (num1 < num2)
	  result = num1;
	else
		result= num2;
	
	return result;
} //end of minRate

 
 } //end of class

When I run this I get the following error:

Enter Hours and Minutes (HH:MM) Pulse Was Taken: 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.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at MaxTest.main(MaxTest.java:18)

 
My suggestion is to treat all inputs as Strings.

Then, if the conversion to int works, it's a rate. If not, use the split method to get hour and minute and compare.

Cheers,
Dian
 
Below is a "Clock" class I made to use in a timer application. You can set it with a "HH:MM" or "HH:MM:SS" string. It also has a built in counter: increment().

Code:
/*
 * Clock.java
 *
 * Created on March 15, 2007, 4:20 PM
 *
 */
package timetracker;

import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
 * The Clock class manages a set of hours, minutes, and seconds. (The Calendar 
 * class could have been used, but this was a learning experience.) 
 * String set format can be HH:MM or HH:MM:SS with default values of zero.
 *
 */
public class Clock extends java.lang.Object implements Cloneable {
    private int h,m,s; // Hours, minutes, seconds of this clock
    
    /** Creates a new instance of Clock, setting all values to zero */
    public Clock() {
        reset();
    }

    /** Create new Clock, setting hour and minutes to input ints, seconds to 0 */
    public Clock(int hour, int minute) throws IndexOutOfBoundsException {
        set(hour,minute,0);
    } 
    
    /** Create new Clock, setting values to input ints */
    public Clock(int hour, int minute, int second) throws IndexOutOfBoundsException {
        set(hour,minute,second);
    }    

    /** Creates a new Clock, setting value to input string */
    public Clock(String strInputTime) throws IndexOutOfBoundsException, NumberFormatException {
        set(strInputTime);
    }

    /** Sets the clock to a given value */
    public void set(int hour, int minute, int second ) throws IndexOutOfBoundsException {
        if( validInput( hour,minute,second) ) {
            h=hour;
            m=minute;
            s=second;
            rollover();
        } else {
            throw new IndexOutOfBoundsException("Attempt to set Clock to invalid value");
        }
    }

    /** Sets the clock to a value from a String*/
    public void set(String strInputTime ) throws IndexOutOfBoundsException, NumberFormatException {
        Pattern pattern = Pattern.compile( "(\\d*):(\\d*):?(\\d*)" );
        Matcher matcher = pattern.matcher(strInputTime);
        int hour,minute,second;
        hour=minute=second=0;
  
        if( matcher.find() ) {
            hour=  strToInt(matcher.group(1));
            minute=strToInt(matcher.group(2));
            second=strToInt(matcher.group(3));
            set(hour,minute,second);
        } else {
            throw new NumberFormatException("Could not find a time value matching regular expression: " + pattern.toString());
        }
    }
    
    /** Return the integer equivalent of a string, setting "" to zero */
    private int strToInt(String strNum) throws NumberFormatException {
        if( strNum.length()>0 ) {
            return Integer.valueOf(strNum);
        } else {
            return 0;
        }
    }
    
    /** Sets all values to zero */
    public void reset() {
        h=m=s=0;
    }
    
    /** 
     * Checks range of numbers to fit within Ingeger constraints.
     *
     * @return  if the input is within bounds, return true.
     */
    public boolean validInput(int hour, int minute, int second ) {
        if( hour>=0 && minute>=0 && second>=0 &&
                second < Integer.MAX_VALUE && 
                (minute + second/60) < Integer.MAX_VALUE &&
                (hour + minute/60 + second/3600) < Integer.MAX_VALUE ) {
            return true;
        } else {
            return false;
        }
    }
    
    public int getHour() {
        return h;
    }

    public int getMinute() {
        return m;
    }
        
    public int getSecond() {
        return s;
    }
    
    /** Returns the clock value in a string. */
    public String toString() {  
        // Todo: accept format string to customize output
        return pad(h) + ":" + pad(m) + ":" + pad(s);
    }
    
    /*  public boolean equals(Object obj) {
        // Compares two Clocks for equality
        if( obj instanceof Clock ) {
            return ((((Clock)obj).getHour() == h) && 
                    (((Clock)obj).getMinute() == m) && 
                    (((Clock)obj).getSecond() == s));
        } else {
            return false;
        }       
    }
     */
    
    /** Make the clock tick one second */
    public void increment() {
        s++;
        rollover();
    }

    /** 
     * Adds a given number of minutes.  Use a negative number to subtract minutes.
     * If the number goes out of bounds ( < 0 ), an exception is thrown.
     */
    public void shiftMinutes( int minutes ) throws IndexOutOfBoundsException {
        int totalSeconds;
        totalSeconds = (h*60*60) + (m*60) + s + (minutes * 60);
                
        if( totalSeconds < 0 ) {
            throw new IndexOutOfBoundsException("Attempt to set Clock to invalid value");
        }
        
        reset();
        s = totalSeconds;        
        rollover();
    }    
    
    /** Make 60 spill over to increment 1 minute and reset, etc. */
    private void rollover() {
        if( s>=60 ) {
            m+=s/60;
            s=s%60;
        }  
        if( m>=60 ) {
            h+=m/60;
            m=m%60;
        }
    }
    
    /** Zero pad single digit numbers to two digits 
     *
     * @return string value of the number, prefixed by a zero if one digit (num<10 && num>=0)
     */
    private String pad(int num) {
        if( num<10 && num>=0 ) {
            return "0" + String.valueOf(num);
        } else {
            return String.valueOf(num);
        }
    }
    
    /** Clones current clock. 
     *
     * @return new instance of Clock with h:m:s set to current object's values
     **/
    public Clock clone() {
        Clock myClone = new Clock();
        myClone.h = this.h;
        myClone.m = this.m;
        myClone.s = this.s;
        return myClone;
    }
}
 
Just a detail. Instead of using the methods maxRate and minRate you could use Math.max and Math.min

Code:
maxPulseRate = Math.max(pulseRate,maxPulseRate);
minPulseRate = Math.min(pulseRate,minPulseRate);

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top