Оператор переключения в l oop с неизвестным количеством повторений - PullRequest
0 голосов
/ 06 апреля 2020

Привет, я делаю небольшую задачу, где мне нужно собрать все oop с неизвестным количеством повторений. У меня проблема с моим кодом, когда пользователь вводит символ бесконечно. Как мне это исправить?

String[] action = {"x", "u", "d", "l", "r", "s", "h", "e"}; 

        System.out.println("Please enter an action");

    String input = sc.next();

    char selection;

        do{
            selection = input.charAt(0);

        switch(selection){

            case 'x': System.out.print("Bye!"); 
                break;
            case 'u' : System.out.print("You go one square up.");
                break;
            case 'd': System.out.print("You go one square down.");
                break;
            case 'l': System.out.print("You go one square left.");
                break;  
            case 'r': System.out.print("You go one square right.");
                break;      
            case 's': System.out.print("You search the square for treasure. You find nothing.");
                break;  
            case 'h': System.out.print("You hide, waiting for enemies to come by. It gets boring after about an hour and a half, so you give up.");
                break;  
            case 'e': System.out.print("You eat some food. You regain 0 hit points");
                break;
            case 'z': 
                break;
            default: 
                System.out.println("I dont understand");
                break;
        }
        }
            while (selection != 'z');
        ```

Ответы [ 3 ]

0 голосов
/ 06 апреля 2020

Вам нужно также ввести пользовательский ввод в do-while l oop. Поэтому он запрашивает новый ввод после каждой итерации. Я в настоящее время на моем телефоне, поэтому я не могу показать вам. Но это легко исправить.

0 голосов
/ 06 апреля 2020

Прежде всего, вам необходимо прочитать ввод за символом. Поскольку вы уже взяли слово, вам нужно начать с индекса 0 и продолжить переход к следующему символу в do-while l oop. Для этого:

String[] action = {"x", "u", "d", "l", "r", "s", "h", "e"}; 
        System.out.println("Please enter an action:");
        Scanner sc = new Scanner(System.in);
    String input = sc.next();
    char selection;
    int i = 0;
        do{
            selection = input.charAt(i++);

        switch(selection){

            case 'x': System.out.print("Bye!"); 
                break;
            case 'u' : System.out.print("You go one square up.");
                break;
            case 'd': System.out.print("You go one square down.");
                break;
            case 'l': System.out.print("You go one square left.");
                break;  
            case 'r': System.out.print("You go one square right.");
                break;      
            case 's': System.out.print("You search the square for treasure. You find nothing.");
                break;  
            case 'h': System.out.print("You hide, waiting for enemies to come by. It gets boring after about an hour and a half, so you give up.");
                break;  
            case 'e': System.out.print("You eat some food. You regain 0 hit points");
                break;
            case 'z': 
                break;
            default: 
                System.out.println("I dont understand");
                break;
      }
    } while (i < input.length() && selection != 'z');

В while() должно быть другое условие, чтобы избежать превышения размера входной строки. Кроме того, я не мог понять, зачем вам массив String action, который вы создали в начале.

0 голосов
/ 06 апреля 2020

sc.next() останавливает выполнение до тех пор, пока пользователь не введет данные. Однако, поскольку он находится за пределами l oop, он не остановится для чтения нового ввода. Поэтому вам необходимо переместить вызов next() в l oop.

do{
  String input = sc.next();
  selection = input.charAt(0);

  switch(selection){
  // rest of the code

}
...