If-Else Strings

Given the string and integer x, return a new line with the first x characters of the original string now at the end. Make sure that characters are enough trying to move them to the end of the line.

Data examples: Data file: stringChopper.dat

apluscompsci 3
apluscompsci 5
apluscompsci 1
apluscompsci 2
apluscompsci 30
apluscompsci 4

Output Example: (output must be accurate)

uscompsciapl
compsciaplus
pluscompscia
luscompsciap
no can do
scompsciaplu

My code is:

public class StringChopperRunner_Cavazos {
   public static void main(String[] args) throws IOException {
      Scanner fileIn = new Scanner(new File("stringChopper.dat"));

      while(fileIn.hasNext()) {
      System.out.println(StringChopper.chopper(fileIn.next(), fileIn.nextInt()));
      }
   }
}

class StringChopper { 
   public static String chopper(String word1, int index) {
      if(word1.length() < index - 1){
         return "no can do";
      }
      else {
         return word1;
      } 
   }
}

 So my question is: How can I return a String with the specified index number if it is less than to make sure that there are letters EOUGH?

+4
source share
1 answer

Use String#substringto find different parts of a string and then combine them together using an operator +.

if (word1.length() < index - 1){
    return "no can do";
} else {
    return word1.substring(index) + word1.substring(0, index);
}
+2
source

Source: https://habr.com/ru/post/1687450/


All Articles