3
import java.util.*;

class Test{
    private int intToken;       
    public Test(){
        intToken = 0;          
    }
    // A method that returns the last character of a String
    // This here returns a string regardless of input
    public String lastChar(String tok){
        String token = String.valueOf(tok);
        String strToken = token.substring(token.length()-1);
        return strToken;
    }
    public static void main(String[]args){
        Test test = new Test();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a number to get its last number");
        String value = scan.nextLine();
        System.out.println(test.lastChar(value));  
    }
}

The code above method lastChar() works for both Integer and String. Since I am practicing programming, I really wanted to create a single method that returns either a String or Integer but within the method I wanted to detect if the input is an Integer or String.

Just after the methods creation, I first experimented with

Scanner scan = new Scanner(tok);
scan.hasNextInt(); 

returned false even when there was int in tok.

I also tried

tok.contains("0,1,2,3,4,5,6,7,8,9"); 

It also returned false even when there was int in tok. I have yet to study char type. but what I noticed was that tok.contains("1"); returned true.

I wanted to use the boolean result to create separate handlers for String and Integer. Well the code works so far.

Now my question is if it is a safe or good practice to use a single method like lastChar(), or should I define two separate methods lastInt() and lastStr()

Huang Chen
  • 1,177
  • 9
  • 24
  • Numbers have digits (which are one-digit numbers). Internally, they are not stored in base-10, so you have to convert them to base-10 to get the last digit. – tucuxi Jul 10 '15 at 13:58
  • I wish I understood clearly what that meant. But giving an example wish definitely add to my knowledge. I was trying to get the last character from bunch of characters Comprising numbers,int,control char etc. –  Jul 10 '15 at 14:01

5 Answers5

4

I you want to know if the value of a String is an integer (like "1234"), you can try to convert the String: if there is an exception the value of the String is not an integer:

try{
   Integer.parseInt(tok);
   return true;
} catch(NumberFormatException ex) {
   return false;
}
andynaz
  • 56
  • 4
  • Using an exception in this way is bad practice -- exceptions are extremely slow. Better to check that the string contains only digits before trying to parse it. Alternatively write your own integer parser (not difficult) that can gracefully handle non-integer strings. – rossum Jul 10 '15 at 14:08
  • What of case were you have Strings mixed with int? , you wont know if it was purely int, or mainly Strings. What I want to achieve is to test tok if there is any int in it, then I will treat it as a String, and also test if there is any special character be it alphabet other than int, if it returns false, then I will treat it as an int –  Jul 10 '15 at 14:10
  • This is horribly inefficient as multiple inputs would slow the entire thing down, why upvote? – Huang Chen Jul 10 '15 at 14:10
  • @rossum: interesting... I could check with a regex or checking every character in the string... but what if a string contains all digits but it is too long to fit an int/Integer? – andynaz Jul 10 '15 at 15:33
  • You can easily check the length of the `String` parameter. Short strings convert directly to an `int`. With a longer string, convert it to a `long` and then check that it is is `<= Integer.MAX_VALUE`. If the string is too big for any possible integer then take whatever action you want for a non-integer string. – rossum Jul 10 '15 at 16:38
  • and all this (cheching the format, check lenght, conversion in long) is more efficient than the try/catch strategy? – andynaz Jul 12 '15 at 11:14
0
Scanner scan = new Scanner("tok');

This should either be single quotes or double quotes, not both

Also hasNextInt() defines whether the next scanner token is an int, of course it would return false since your input doesn't have an int

tok.contains("1"); 

This is checking if it contains the string "1" not the number 1

Your method returns a String, not both a String and an Int. Even if you input "1" it will be treated as a String

You should learn more about the methods and what they return

How to check the input is an integer or not JAVA?

You can always test the input and use the NumberFormatException or MismatchInputException

Community
  • 1
  • 1
Huang Chen
  • 1,177
  • 9
  • 24
  • Will defining multiple int say int one = 1; int two =2; and passing them to tok,contains(one,two); work? Because tok.contains(0,1,2.3,4 etc 9); does not work –  Jul 10 '15 at 14:16
  • Please read the api for String contains() method http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence) – Huang Chen Jul 10 '15 at 14:22
0

Take a look at https://docs.oracle.com/javase/tutorial/java/data/index.html It talks about the differences between numbers and strings in Java. You would definitely need two methods if you want to return two different data types.

Claysmile
  • 21
  • 3
0

A little addition to the answers from andynaz and Huang Chen
to prevent catch based programming it's encourged to use googles Guava Library
in the library you have Ints.tryParse(String str)
wich returns null if str cannot be parsed
and a parsed Integer from str otherwise

hoped this answered your question

0

If you're practicing programming, you can loop over the characters in the string and detect if one is a digit via Character class

    String x = getString();
    boolean hasNonDigits = false;
    for(char c : x.toCharArray()){
        if(!Character.isDigit(c)){
            hasNonDigits = true;
            break;
        }
    }
    if(hasNonDigits){
        // It's not an integer
    }

But if you are looking for a more conventional way, use regex with Pattern

    Pattern p = Pattern.compile("\\D");
    String x = getString();
    boolean isInteger = !p.matcher(x).find();
MadConan
  • 3,749
  • 1
  • 16
  • 27