Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a safe programming practice?

Tags:

java

string

int

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()


1 Answers

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;
}
like image 51
andynaz Avatar answered Jan 01 '26 11:01

andynaz