2013-02-12 2 views
1

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

/* 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!"); 
    } 
    } 

ответ

5

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

Просто разместите эти заявления после случая default: в заявлении дела, и он должен работать.

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

... 
    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(); 
    } 
} 

к:

 ... 
    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(); дважды.

+0

У меня есть ответ = kb.nextLine(); дважды, потому что по какой-то причине программа не будет приостанавливать ввод данных пользователем. Но когда я сделал то, что вы сказали об изменении}, он не вернулся к утверждению while в начале. – SMoore

+0

Ничего, я понимаю, что мне нужно было переместить чтение ввода пользователя. Большое вам спасибо за помощь! – SMoore

0

Это должно сделать трюк

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!"); 
    } 
} 
+0

Проблема в том, что мне понадобится, чтобы ответ был ложным, если пользовательский ввод - нет. – SMoore

+0

Я отредактировал свой ответ .... если проблема решена, отметьте ответ как разрешенный для использования в будущем. – wcraft