Бесконечный цикл или раннее завершение цикла do while

Я уже некоторое время борюсь с этой программой. Он начал правильно компилироваться, но когда я запускаю его как есть, он бесконечно говорит «Ваш счет __». Когда я изменяю начальное значение ответа, он отказывается работать. Я в растерянности, как это исправить.

/* Savannah Moore
   CSCI 1301
    2/11/2013
    Internet Package Code: Code determines customer's final pricing. */
import java.util.Scanner;

public class internet{
    public static void main(String[] args){
      double hours, price;
      int internet;
      String response, check="Yes";


      Scanner kb = new Scanner(System.in); /* This sections questions the user as to which package they have bought. */
       System.out.println("Our internet packages include:");
        System.out.println("Package 1: For $9.95 per month, 10 hours of access are provided. Additional hours are $2.00 per hour.");
        System.out.println("Package 2: For $13.95 per month, 20 hours of access are provided. Additional hours are $1.00 per hour.");
        System.out.println("Package 3: For $19.95 per month, unlimited access is provided.");
        System.out.println("Please enter your package number:");
       internet=kb.nextInt();
        System.out.println("Please enter your total hours used:");
       hours=kb.nextDouble();   
        response = "Yes";

while(check.compareToIgnoreCase(response)== 0)
  {
      switch (internet)
      {
      case 1: 
              {  if (hours > 10)
                       price = (hours-10)*2 + 9.95; /* This adds the additional hours to the user's price at the current overage rate. */
                    else    
                        price = 9.95;
                }
              System.out.println("Your bill is $" +price);  
               break; 
      case 2: 
              {  if (hours > 20)
                       price = (hours-20) + 13.95;
                    else    
                        price = 13.95;
                }
              System.out.println("Your bill is $" +price);  
               break;        
     case 3:System.out.println("Your bill is $19.95");  
                break; 
      default: System.out.println("This package choice is invalid.");

      System.out.println("Would you like to compare your price with that of another package? Yes or No"); /* This gives the user the ability to stop the loop. */
      response=kb.nextLine();
      response=kb.nextLine();   
     }
    }

    System.out.println("Thank you for using us as your internet service provider.  Have a nice day!");
    }
    }

person SMoore    schedule 12.02.2013    source источник


Ответы (2)


Цикл становится бесконечным, потому что шансы пользователя изменить ответ на «Нет» находятся внутри оператора case. Таким образом, когда вы break; выходите из оператора case, вы сразу же возвращаетесь к проверке «пока», а поскольку response и check по-прежнему имеют значение «Да», это не так. все это снова.

Просто поместите эти операторы после default: в оператор case, и он должен работать.

Другими словами, изменить:

   ...
   default: System.out.println("This package choice is invalid.");

   System.out.println("Would you like to compare your price with that of another package? 
       Yes or No"); /* This gives the user the ability to stop the loop. */
   response=kb.nextLine();
   response=kb.nextLine();   
  }
}

to:

     ...
     default: System.out.println("This package choice is invalid.");
   }
   System.out.println("Would you like to compare your price with that of another package? 
        Yes or No"); /* This gives the user the ability to stop the loop. */
   response=kb.nextLine();
   response=kb.nextLine();   
}

Я не знаю, почему ты делаешь response=kb.nextLine(); дважды.

person mcalex    schedule 12.02.2013
comment
У меня есть ответ=kb.nextLine(); строку дважды, потому что по какой-то причине программа не будет приостанавливаться для пользовательского ввода без нее. Но когда я сделал то, что вы сказали об изменении }, он не вернулся к оператору while в начале. - person SMoore; 12.02.2013
comment
Неважно, я понимаю, что мне нужно было переместить чтение пользовательского ввода. Большое спасибо за помощь! - person SMoore; 12.02.2013

Это должно помочь

import java.lang.*;
import java.util.Scanner;

public class Program
{
    /**
     * This is the main entry point for the application
     */
  public static void main(String[] args){
      double hours, price;
      int internet;
      String response, check="Yes";


        response = "Yes";

while(check.compareToIgnoreCase(response)== 0)
  {

      Scanner kb = new Scanner(System.in); /* This sections questions the user as to which package they have bought. */
       System.out.println("Our internet packages include:");
        System.out.println("Package 1: For $9.95 per month, 10 hours of access are provided. Additional hours are $2.00 per hour.");
        System.out.println("Package 2: For $13.95 per month, 20 hours of access are provided. Additional hours are $1.00 per hour.");
        System.out.println("Package 3: For $19.95 per month, unlimited access is provided.");
        System.out.println("Please enter your package number:");
       internet=kb.nextInt();
        System.out.println("Please enter your total hours used:");
       hours=kb.nextDouble();   
      switch (internet)
      {
      case 1: 
              {  if (hours > 10)
                       price = (hours-10)*2 + 9.95; /* This adds the additional hours to the user's price at the current overage rate. */
                    else    
                        price = 9.95;
                }
              System.out.println("Your bill is $" +price);  
               break; 
      case 2: 
              {  if (hours > 20)
                       price = (hours-20) + 13.95;
                    else    
                        price = 13.95;
                }
              System.out.println("Your bill is $" +price);  
               break;        
     case 3:System.out.println("Your bill is $19.95");  
                break; 
      default: System.out.println("This package choice is invalid.");
      }
      System.out.println("Would you like to compare your price with that of another package? Yes or No"); /* This gives the user the ability to stop the loop. */
      response=kb.nextLine();
      response=kb.nextLine();   

    }

    System.out.println("Thank you for using us as your internet service provider.  Have a nice day!");
    }
}
person wcraft    schedule 12.02.2013
comment
Проблема в том, что мне нужно, чтобы ответ был ложным, если пользовательский ввод нет. - person SMoore; 12.02.2013
comment
Я отредактировал свой ответ .... если проблема решена, отметьте ответ как решенный для дальнейшего использования. - person wcraft; 12.02.2013