简体   繁体   中英

How do I write a method which returns characters of a string?

How would I write a method using a substring which returns the first 10 characters of a string? This is what I have so far but I keep getting an error message saying I need a return statement.

public String firstTen(String number) {
    number.substring(0, 10);

    System.out.println(number);

you need to return in your method:

public static void main(String[] args) {
    System.out.println(firstTen("Hello World Java"));
}

public static String firstTen(String number) {
    return number.substring(0, 10);
}

if the string length is less then 10 then it will cause error to prevent from it you can check it as below:

public static String firstTen(String number) {
    return number.length() > 10 ? number.substring(0, 10) : number;
}
public String firstTen(String number) {
return  number.substring (0,10);
}

You can simply return the result of substring . If it is possible for the String to be less than 10 characters, you may also want the end index to be the minimum of 10 and the length of the String to avoid a StringIndexOutOfBoundsException .

public String firstTen(String number) {
   return number.substring (0, Math.min(10, number.length()));
}

Your answear

public String firstTen(String number)
{
    return number.substring(0, 10);
    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM