Нужно изменить этот код с помощью switch case

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ArrayList <String> toDoList = new ArrayList<>();
        System.out.println("Введите команду (Add (№) дело, delete №, edit № дело, list).");
        while(true){

            Scanner scanner = new Scanner(System.in);
            String str = scanner.nextLine();

            String [] words = str.split("\\s");
            if (words.length == 1){
                for (int i = 0; i < toDoList.size(); i++){
                    System.out.println(i + " " + toDoList.get(i));
                }
            }

            else{
                String index = words[1].replaceAll("[^0-9]", "");
                String item = str.substring(str.indexOf(' ')).trim();

                if (words.length == 2) {
                    if (words[0].equalsIgnoreCase("DELETE")){
                        int indexValue = Integer.parseInt(index);

                        if (indexValue >= toDoList.size()){
                            System.out.println("Номер дела введён неверно!");
                        }
                        else {
                            toDoList.remove(indexValue);
                        }
                    }

                    else if(words[0].equalsIgnoreCase("ADD")){
                        toDoList.add(item);
                    }
                }

                else if (words.length > 2){
                    String itemWOIndex = item.substring(item.indexOf(' ')).trim();

                    if (index.isEmpty()){
                        toDoList.add(item);
                    }

                    else {
                        int indexValue = Integer.parseInt(index);

                        if (words[0].equalsIgnoreCase("ADD")){
                            if (indexValue >= toDoList.size()){
                                toDoList.add(itemWOIndex);
                            }
                            else if (indexValue < toDoList.size()) {
                                toDoList.add(indexValue, itemWOIndex);
                            }
                            else{
                                toDoList.add(item);
                            }
                        }

                        else if (words[0].equalsIgnoreCase("EDIT")){
                            if (indexValue > toDoList.size()){
                                System.out.println("Номер дела введён неверно!");}
                            else {
                                toDoList.remove(indexValue);
                                toDoList.add(indexValue, itemWOIndex);
                            }
                        }
                    }
                }
            }
        }
    }
}

Ответы (1 шт):

Автор решения: Igor
switch(words.length) {
  case 0:
    break;
  case 1:
    ...
    break;
  case 2:
    ...
    break;
  default:
    ...
}
→ Ссылка