The Artima Developer Community
Sponsored Link

Java Answers Forum
How to get type from the input?

11 replies on 1 page. Most recent reply: Aug 20, 2003 1:08 AM by David

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 11 replies on 1 page
Dor

Posts: 13
Nickname: eis
Registered: Jul, 2003

How to get type from the input? Posted: Aug 14, 2003 7:18 AM
Reply to this message Reply
Advertisement
Hi, everyone.

I am trying to write a program to read in a textfile of parameters. All the parameters are one type of integer, float number, or just any arbitrary combination of symbols and alphabets.

Since I have to output this into an excel file and also to do some comparation, I have to 'read' out the exact type of the parameters. I find it especially hard to separate numbers from strings, because I don't think it possible to find some succinct method to check if all elements contained in a certain input parameter are numbers(or at most containing a '.').

Any help is highly appreciated! Thx!


David

Posts: 150
Nickname: archangel
Registered: Jul, 2003

Re: How to get type from the input? Posted: Aug 14, 2003 7:58 AM
Reply to this message Reply
This doesn't sound very difficult. Maybe I'm missing something. Please give a specific example.

Joe Parks

Posts: 107
Nickname: joeparks
Registered: Aug, 2003

Re: How to get type from the input? Posted: Aug 14, 2003 10:35 AM
Reply to this message Reply
The jakarta commons-lang library has a class called StringUtils, with methods like
public static boolean isNumeric(String stringToTest)

http://jakarta.apache.org/commons/lang.html

Dor

Posts: 13
Nickname: eis
Registered: Jul, 2003

Re: How to get type from the input? Posted: Aug 14, 2003 1:20 PM
Reply to this message Reply
Blush, actually it might not be very difficult at all, just I have no experience in that.

The problem is like this, I am given a file of various parameters, the actual type could be Integer, or Float, or (arbitrarily combined) String. For instance, abc=4, xy=3.7, ijk=*8,... things like that. And I'll input the part after "=".

It's important that I separate the numbers from the strings, because I need to make comparison among the former, while the latter is not so much of interest.

I wonder if there's some succinct function to manage that.

That's it. Please help!

Mr Plow

Posts: 18
Nickname: mrplow
Registered: Jun, 2003

Re: How to get type from the input? Posted: Aug 14, 2003 4:56 PM
Reply to this message Reply
I don't think there is a prefabricated method that can do exactly what you need, but you can write your own by expanding on the functionality in java.lang.Character.isDigit(char c).

The code below has a static isNumber() method that returns true if the String input is either a legitimate integer or floating point number. (Note that it does not work for negative numbers, since Character.isDigit returns false when the input is '-' as in "-1.0"). If you need this functionality I suggest adding logic that uses String.startsWith(String s)


public class Tester
{  
public static void main(String[] args)  
{    
String[] stringArray = {"A total String", "A 123", "123oStart", "2", "2.3", "2.3.2", "2..3", ".2", ".X", "123.456"};	
for(int i = 0; i < stringArray.length; i++)	  
System.out.println(isNumber(stringArray[i]));  
}  
 
public static boolean isNumber(String input)  
{    
  boolean decimalAlreadyUsed = false;    
  char[] charArray = input.toCharArray();        
  for(int i = 0; i < charArray.length; i++)    {      
    boolean isDigit = Character.isDigit(charArray[i]);      
    if(isDigit)      {         
      continue;      } 
	else {        
      if(charArray[i] == '.')        {	  
        if(decimalAlreadyUsed)	  {            
          return false;          } 
		else {            
          decimalAlreadyUsed = true;          
		}        
      }else{          
	    return false;        
	  }      
	}//end of if/else    
  }//end of for loop    
  return true;  
}//end of method isNumber};
}//end of class

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: How to get type from the input? Posted: Aug 14, 2003 5:14 PM
Reply to this message Reply
Hmm. Couldn't you just try Integer.parseInt(), then try Double.parseDouble() (or Float.parseFloat(), if you like) and leave all else as String?

Mr Plow

Posts: 18
Nickname: mrplow
Registered: Jun, 2003

Re: How to get type from the input? Posted: Aug 14, 2003 11:53 PM
Reply to this message Reply
Sure you could write a method using the wrapper methods you listed as long as you are use try/catch blocks to catch the NumberFormatExceptions that will be thrown.

The issue really is whether you should. I think that it is generally viewed that exceptions should be used for exceptional events, not to control the flow of a program.

If I remember correctly the Joshua Bloch "Effective Java" book has an item on this, pretty much saying the same thing. I don't have the book in front of me so I can't be more specific.

Regards.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: How to get type from the input? Posted: Aug 15, 2003 1:18 PM
Reply to this message Reply

> Sure you could write a method using the wrapper methods
> you listed as long as you are use try/catch blocks to
> catch the NumberFormatExceptions that will be thrown.


That was exactly what I meant by "try" (I made it bold, but that probably wasn't explicit enough, since in both cases it was next to other text that was bold).

> The issue really is whether you should. I think that it
> is generally viewed that exceptions should be used for
> exceptional events, not to control the flow of a program.


Generally, perhaps, but not always. In this case I like the idea of having the same code that does the tranformation also do the validation. You can do all kinds of checks on the string's format to try and determine whether parseInt() or parseFloat() will like it and still be wrong. Regardless of how much pre-checking you do, you still need to catch the NumberFormatException. Additionally, your pre-checking may be flawed and you might filter out some things that would have been acceptible (for example, if you forgot to include the minus sign in your filter).

By the way, the NumberFormat class has some things that will help with this problem.


> If I remember correctly the Joshua Bloch "Effective Java"
> book has an item on this, pretty much saying the same
> thing. I don't have the book in front of me so I can't be
> more specific.


I don't think Josh is a doctrinaire, so I'm sure he couched this advice in the "prefer this technique" form, as he does commonly in Effective Java (this is a good practice that was also used in Scott Meyer's Effective C++ books).

I think what he is arguing against is capricious use of exceptions. For example, this code works fine, but is a bad use of exceptions:
import java.io.PrintStream;
 
public class BadUseOfException
{
   public static void main(String args[])
   {
      printNumberList( new int []{ 4, 3, 2, 1 }, System.out );
   }
 
   static void printNumberList( int [] numbers, PrintStream stream )
   {
      try
      {
         for( int i = 0; i < Integer.MAX_VALUE; i++ )
            stream.println( i + ". " + numbers[i] );
      }
      catch( ArrayIndexOutOfBoundsException aioobe )
      {
         stream.println("That's all, folks!");
      }
   }
}


It is bad because it confuses the reader. Someone who sees this code will be a bit perplexed that you didn't use the array length and waste time to figure out why you are using this unusual technique.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: How to get type from the input? Posted: Aug 15, 2003 1:23 PM
Reply to this message Reply
Oops -- I got timed-out, so my preview was posted before I had a chance to correct "acceptible" to "acceptable."

Mr Plow

Posts: 18
Nickname: mrplow
Registered: Jun, 2003

Re: How to get type from the input? Posted: Aug 15, 2003 1:38 PM
Reply to this message Reply
Matt -

Good points. Certainly your suggestion to use the parse???() methods makes for much simpler code. I stand corrected.

Regards.

Dor

Posts: 13
Nickname: eis
Registered: Jul, 2003

Re: How to get type from the input? Posted: Aug 18, 2003 3:48 AM
Reply to this message Reply
Thank you all!

David

Posts: 150
Nickname: archangel
Registered: Jul, 2003

Re: How to get type from the input? Posted: Aug 20, 2003 1:08 AM
Reply to this message Reply
Another idea to check the 'type' of the contents of a String would be to use regular expressions.

Flat View: This topic has 11 replies on 1 page
Topic: Images in JComboBox Previous Topic   Next Topic Topic:

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use