There is a code in which you need to make a cyclic shift of characters (Input 1: qwerty; Input 2: 2; Output => tyqwer)

I wrote the code, it seems to me that it should work correctly, but I ran into the problem of the fact that the array goes beyond its boundaries, which is logical. The question arises, is there any function that allows you to go beyond the array to check?

import java.util.Scanner; public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Write string"); String str = sc.next(); System.out.println("Write number"); int num = sc.nextInt(); char[] symbols = str.toCharArray(); // boolean first = true; int k = 0; for (int i = 0; i < symbols.length; i++) { if((symbols[i+num]) > symbols.length-1){ symbols[k] = symbols[i]; System.out.print(symbols[k]); k++; }else{ symbols[i+num] = symbols[i]; System.out.print(symbols[i+num]); } } } } 

    1 answer 1

    The specific problem is completely solved without arrays:

      Scanner sc = new Scanner(System.in); System.out.println("Write string"); String str = sc.next(); System.out.println("Write number"); int num = sc.nextInt(); for (int i = 0; i < num; i++) { char last = str.charAt(str.length()-1); str = last + str.substring(0, str.length()-1); } System.out.println(str); 

    Using StringBuilder will of course be more correct, but in order not to complicate things this way. Going beyond the array can be checked by comparing the argument with the size of the array or even through an exception. For cyclical rearrangements on an industrial scale, LinkedList is well suited. Sheets have no size limits.