Is there a better way to write s.substring so my code doesn't fail when having one character

  • A+
Category:Languages

When writing 'Hello' as my string, my output is 'He'. The same when writing 'He' as my string, my output is also 'He'. I have added a piece of code that states when the string is bigger then one character, then it should just print the character itself.

This seems very basic but somehow I get an error when only giving one character such as 'H' as my string. It says: String index out of range: 2.

public static void main(String[] args) {      String s = "o";     String s1 = s.substring(0,2);       if (s.length() >= 1 )      {     System.out.println(s);         }     else      {     System.out.println(s1);         }   }  } 

 


Alternative:

s.substring(0, Math.min(2, s.length())) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: