Results 1 to 11 of 11
Like Tree1Likes
  • 1 Post By pbrockway2

Thread: Convert string with leading zero to int

  1. #1
    Join Date
    Apr 2010
    Location
    Warakapola, Sri Lanka
    Posts
    15
    Rep Power
    0

    Default Convert string with leading zero to int

    Hi,
    I need to convert a String with leading zero to integer.

    Eg:
    String numberInString = "01";
    after conversion :::>
    int intWithLeadingZero = 01 or 1.

    I used Integer.parseInt(). But it gives an error message.
    Can any one help me to solve this little problem.

    Thanks.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,932
    Rep Power
    8

    Default Re: Convert string with leading zero to int

    Can you post the exact code (in SSCCE form) that causes the error? Using parseInt() seems to be working fine for me...
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Join Date
    Apr 2010
    Location
    Warakapola, Sri Lanka
    Posts
    15
    Rep Power
    0

    Default Re: Convert string with leading zero to int

    My problem is reading two time inputs(in 24hours clock) and calculating the time interval.
    Code:
    Constructor TimeInterval :-

    Java Code:
      public TimeInterval()
    	{
    		System.out.print("Enter the Start Time : ");
    		startTime = sc.nextInt();
    		System.out.print("Enter the Finish Time : ");
    		finishTime = sc.nextInt();
    	}
    Method for calculate Hours :-
    Java Code:
    public int getHours()
    	{
    		String startTimeInString = Integer.toString(startTime);
    		String startHourInString = startTimeInString.substring(0, 2);
    		int startHour = Integer.parseInt(startHourInString);
    
    
    		String finishTimeInString = Integer.toString(finishTime);
    		String finishHourInString = finishTimeInString.substring(0, 2);
    		int finishHour = Integer.parseInt(finishHourInString);
    
    
    		int hours = Math.abs(finishHour - startHour);
    
    
    		return hours;
    	}
    method for calculate minutes not given here.
    In the tester class when I enter time without leading zero ( Eg: 1200) it gives correct answer. (Method hasn't completed with fully functionaly). But, when I enter times like 0930, It gives an error message:

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,932
    Rep Power
    8

    Default Re: Convert string with leading zero to int

    What line is that error on? What String are you trying to access? How many indexes does it have? What index are you trying to access?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Convert string with leading zero to int

    What source code line do you get the error on?
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,945
    Rep Power
    19

    Default Re: Convert string with leading zero to int

    You are taking the 4 digit time and turning it into an int.
    That int will not have leading zeros (that is a meaningless concept for an int).
    so 0930 will become 930.
    You then change it into a String, which will be "930".
    ANd there is your problem.

    You should be reading the time in as a String from the start, since it is not a meaningful int.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    Join Date
    Apr 2010
    Location
    Warakapola, Sri Lanka
    Posts
    15
    Rep Power
    0

    Default Re: Convert string with leading zero to int

    Sorry for the inconvenience.
    Here are the both classes and error message. It may confuse you because, these codes may not clear. there aren't comments for constructor or methods. I think they don't need.
    1. TimeInterval class.
    Java Code:
    import java.util.Scanner;
    
    
    public class TimeInterval
    {
    	Scanner sc = new Scanner(System.in);
    
    
    	private int startTime;
    	private int finishTime;
    
    
    	public TimeInterval()
    	{
    		System.out.print("Enter the Start Time : ");
    		startTime = sc.nextInt();
    		System.out.print("Enter the Finish Time : ");
    		finishTime = sc.nextInt();
    	}
    
    
    	public int getHours()
    	{
    		String startTimeInString = Integer.toString(startTime);
    		String startHourInString = startTimeInString.substring(0, 2);
    		int startHour = Integer.parseInt(startHourInString);
    
    
    		String finishTimeInString = Integer.toString(finishTime);
    		String finishHourInString = finishTimeInString.substring(0, 2);
    		int finishHour = Integer.parseInt(finishHourInString);
    
    
    		int hours = Math.abs(finishHour - startHour);
    
    
    		return hours;
    	}
    
    
    	public int getMinutes()
    	{
    		String startTimeInString = Integer.toString(startTime);
    		String startMinuteInString = startTimeInString.substring(2, 4);
    		int startMinute = Integer.parseInt(startMinuteInString);
    
    
    		String finishTimeInString = Integer.toString(finishTime);
    		String finishMinuteInString = finishTimeInString.substring(2, 4);
    		int finishMinute = Integer.parseInt(finishMinuteInString);
    
    
    		int minutes = Math.abs(finishMinute - startMinute);
    
    
    		return minutes;
    	}
    }
    2. TimeIntervalTester class
    Java Code:
    public class TimeIntervalTester
    {
    	public static void main(String args[])
    	{
    		TimeInterval interval = new TimeInterval();
    
    
    		System.out.println(interval.getHours()+ " : " +interval.getMinutes());
    	}
    }
    3. Error message

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.String.substring(Unknown Source)
    at TimeInterval.getMinutes(TimeInterval.java:36)
    at TimeIntervalTester.main(TimeIntervalTester.java:7)
    These classes have many run time errors like, output for times 1030 and 1200. But, I need first, solve basic problems.
    If you have time, give me a full description.
    Thanks.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Convert string with leading zero to int

    You should check the length of the String you are trying to use subtstring on and make sure it is long enough. Your code assumes it has 4 characters.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    FOX427 is offline Member
    Join Date
    Jun 2011
    Posts
    54
    Rep Power
    0

    Default Re: Convert string with leading zero to int

    Hi darshanaprasad!

    I had the same problem as you, I guess we both using same book to train our coding skills:) I spent few hours to try how to construct getHours and getMinutes methods you used here, I knew that I had to use parseInt but I just couldn't use it in a right way(have to read that part from book again), and eventually I copied your methods(slightly changed as I had another names for parameters)....After looking at code I found that you had interval (0, 2) instead of (0, 1) and (2, 4) instead of (2, 3); you can see that now the code is working if you put values - 0900 and 1730...But when you enter 0900 and 0435 you will get 5 hours and 5 minutes instead of 5hours and 35 minutes...I think this is because while subtracting minutes it thinks that there are 100 minutes instead of 60, therefore we need to find a way to limit the count to 59/60....
    here is my code:
    Java Code:
    import java.util.Scanner;
    
    public class TimeInterval {
    
    	/**
    	 * @param args
    	 */
    	public TimeInterval()
    	{
    		Scanner in = new Scanner(System.in);
    		
    		System.out.println("Please enter the first time");
    		firstTime = in.nextInt();
    		
    		System.out.println("Please enter the second time");
    		secondTime = in.nextInt();
    		
    	}
    	
    	public int getHours()
    	{
    		String firstTimeInString = Integer.toString(firstTime);
    		String startHourInString = firstTimeInString.substring(0, 1);
    		int startHour = Integer.parseInt(startHourInString);
    		
    		String secondTimeInString = Integer.toString(secondTime);
    		String finishHourInString = secondTimeInString.substring(0, 1);
    		int finishHour = Integer.parseInt(finishHourInString);
    		
    		int hours = Math.abs(finishHour - startHour);
    		return hours;
    	}
    	
    	public int getMinutes()
    	{
    		String firstTimeInString = Integer.toString(firstTime);
    		String startMinuteInString = firstTimeInString.substring(2, 3);
    		int startMinute = Integer.parseInt(startMinuteInString);
    		
    		String secondTimeInString = Integer.toString(secondTime);
    		String finishMinuteInString = secondTimeInString.substring(2, 3);
    		int finishMinute = Integer.parseInt(finishMinuteInString);
    		
    		int minutes = Math.abs(finishMinute - startMinute);
    		return minutes;
    		
    		
    	}
    	private int firstTime;
    	private int secondTime;
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		TimeInterval time = new TimeInterval();
    		System.out.println(time.getHours()+ " hours");
    		System.out.println(time.getMinutes()+ " minutes");
    		
    	}
    	
    
    }

  10. #10
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Convert string with leading zero to int

    Java Code:
    firstTime = in.nextInt();
    
    // ...
    
    public int getHours()
    {
        String firstTimeInString = Integer.toString(firstTime);
        String startHourInString = firstTimeInString.substring(0, 1);
    The dangers of reading an int from the characters typed in, then forming a string from it and taking a substring have been discussed earlier in this thread. substring(0,1) returns a one character string which will be no good at all after 0959 when the string corresponding to the hours has two digits.

    But when you enter 0900 and 0435 you will get 5 hours and 5 minutes instead of 5hours and 35 minutes...I think this is because while subtracting minutes it thinks that there are 100 minutes instead of 60
    Don't you mean 4 hours and 25 minutes? In fact your getMinutes() code is returning 5 for 0435. "0435"-->435-->"435"-->"5"-->5. The step "435"-->"5" is what substring(2,3) does.

    -----

    It would be better to ask questions about your code in your own thread. Tempus fugit, and the OP, too, has probably flown.
    Last edited by pbrockway2; 07-10-2012 at 07:27 AM.
    FOX427 likes this.

  11. #11
    FOX427 is offline Member
    Join Date
    Jun 2011
    Posts
    54
    Rep Power
    0

    Default Re: Convert string with leading zero to int

    it shows 5 hours and 5 minutes as I said, but it doesn't matter, you were right, I will follow your tips :)

Similar Threads

  1. Replies: 3
    Last Post: 02-10-2012, 06:26 PM
  2. Hot to convert string to int ????
    By java_no1 in forum JavaServer Pages (JSP) and JSTL
    Replies: 2
    Last Post: 06-07-2011, 07:40 AM
  3. Replies: 2
    Last Post: 04-25-2011, 04:13 PM
  4. convert string to list
    By isme in forum New To Java
    Replies: 19
    Last Post: 06-16-2010, 09:01 AM
  5. convert obj to string
    By isme in forum New To Java
    Replies: 11
    Last Post: 06-14-2010, 10:54 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •