Z
Z
Zapil2022-01-22 00:17:30
Java
Zapil, 2022-01-22 00:17:30

Java array indexing. How to avoid cycles?

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        char[] array = str.toCharArray();

        //выводы (костыли на циклах)
        char third_symbol = array[2];
        char pre_last_symbol = array[array.length - 2];

        System.out.print(third_symbol + "\n" + pre_last_symbol + "\n");
        // вывод первых пяти символов
        for (int i = 0; i < 5; i++) {
            System.out.print(array[i]);;
        }
        System.out.println(); // перенос строки просто

        //вывод строки без последних двух символов
        for (int i = 0; i < array.length-2; i++) {
            System.out.print(array[i]);
        }
        System.out.println(); // перенос строки просто

        //вывод строки без первых трёх символов
        for (int i = 3; i < array.length; i++) {
            System.out.print(array[i]);
        }
        System.out.println(); // перенос строки просто

        //вывод длины строки
        System.out.print(array.length);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2022-01-22
@Zapil

Good afternoon.
If I were you, I would do the following:
I would create a method that takes several arguments:
1) the array itself, over which you need to
iterate 2) startOffset is if you need to output char without the first n characters
3) endOffset is if you need to output char without the last n characters
Or you can implement something similar using the Stream API. But most likely you are still learning Java and most likely you haven't gotten there yet...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question