Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Bailey Evans   on Nov 15 In Java Category.

  
Question Answered By: Hilma Miller   on Nov 15

This may help  u.

public class TestJava1{
public static void main(String args[]){
if(args.length < 2 ){
System.out.println("Java Usage: Please
provide 2 arguments.");
System.exit(0);
}
isContainsOnlyDigits(args[0], args[1]);
int sum = convertInteger(args[0], args[1]);
if(sum != -1)
System.out.println("The Sum of Two integer
is "+sum);

int lenValue = stringLength(args[0], args[1]);
System.out.println("The length  of the strings  got
from method  is "+lenValue);

int value = stringCompare(args[0], args[1]);
System.out.println("The return value got from method
is "+value);
}

private static void isContainsOnlyDigits(String str1, String
str2) {

/* Using charAt method
String strArr[] = {str1, str2};
boolean isDigit;
for(int i = 0; i < 2; i++){
isDigit = true;
for(int j = 0; j < strArr[i].length(); j++ ){
char a = strArr[i].charAt(j);
Character ch = new Character(a);
if(!ch.isDigit(a)){
isDigit = false;
System.out.println("The
string '"+strArr[i]+"' contains other characters.");
break;

}
else continue;
//System.out.print(" Break is
called ");
}
if(isDigit)
System.out.println("The
string '"+strArr[i]+"' contains only digits.");


}
*/

// direct method.
try{
Integer.parseInt(str1);
System.out.println("The string  '"+str1+"'
contains only digits.");

}catch(Exception e){
System.out.println("The string '"+str1+"'
contains other characters.");

}

try{
Integer.parseInt(str2);
System.out.println("The string '"+str2+"'
contains only digits.");

}catch(Exception e){
System.out.println("The string '"+str2+"'
contains other characters.");

}

}

public static int convertInteger(String str1, String str2) {
try{
int int1 = Integer.parseInt(str1);
int int2 = Integer.parseInt(str2);

return int1+int2;
}catch(Exception e){
System.out.println("Sum of two integers
cannot be found, The entered string is not integer");
return -1;
}
}

public static int stringLength(String str1, String str2){
//System.out.println("str1.compareTo(str2)
=>"+str1.compareTo(str2));
int val = str1.compareTo(str2);
int len1 = str1.length();
int len2 = str2.length();
if(len1 == len2 ) return 0;
if(len1 > len2 ) return 1;
if(len1 < len2 ) return 2;
return -1;
}

public static int stringCompare(String str1, String str2){
System.out.println("str1.compareTo(str2)
=>"+str1.compareTo(str2));
int val = str1.compareTo(str2);
if(val > 0) val = 1;
if (val < 0) val = 2;
return val;
//if(str1.compareTo(str2)){

}

}

Share: 

 
 


Tagged: