Попытка зацикливаться на начале программы - PullRequest
0 голосов
/ 01 февраля 2019

Я не знаю, как перезапустить программу, если введен неправильный ввод.

Я новичок в Java и не знаю, как эффективно использовать операторы if или циклы.

import java.util.Scanner; 

public class TuitionRates 
{
public static void main(String[] args) 
{
    //variables
    String name = "";
    String studentType = "";
    int creditNumber = 0;
    double totalTF = 0.00;
    double studentACTFee = 4.60;
    double parkingFee = 2.00;
    double tuition = 180.40;
    double capitalFee1 = 0.00;
    double capitalFee2 = 21.00;
    double perCreditR = 187.00;
    double perCreditV = 187.00;
    double perCreditD = 187.00;
    double perCreditM = 208.00;
    double perCreditB = 268.00;
    double perCreditO = 387.25;

    Scanner input = new Scanner(System.in);

    //Asking user for Name
System.out.println("Welcome to the NOVA Tuition and Fees Calculator.");
System.out.println("Please enter your name: ");
name= input.nextLine();

//Ask user to choose option

    System.out.println("Please enter the type of student that your are from 
    the choices below:\n"
            + 
            "R for Virginia Resident\r\n" + 
            "M for Military Contract Out-of-State\r\n" + 
            "V for Military Veterans and Dependents\r\n" + 
            "D for Dual Enrolled\r\n" + 
            "B for Business Contract Students\r\n" + 
            "O for Out of State Students\r\n");

    studentType = input.nextLine();
if (studentType.equalsIgnoreCase("R"))
   {

   System.out.println("Please enter the number of credits that you are 
   taking:");
   creditNumber = input.nextInt();

if (creditNumber <= 18)
{
System.out.println("Tuition and fees report for " + name);          
System.out.println("Tuition: "+ tuition);           
System.out.println( "Capital Fee:  \t"+ capitalFee1);           
System.out.println( "Student Activities Fee: \t "+   studentACTFee);            
System.out.println( "Parking Infrastructure Fee: \t " +  parkingFee);           
System.out.println("Tuition & Fees Per Credit: " +  perCreditR);            
System.out.println("X Number of Credits: " + creditNumber);
totalTF = creditNumber * perCreditR;            
System.out.println("Total Tuition and Fees: \t" +  totalTF);
System.out.println("Bodly NOVA");
}

else {System.out.println("Please re-enter credit Number ");}
}

Я хочу, чтобы моя программа перезапускала оператор if, если количество кредитов превышает 18. Поэтому, если бы я ввел 19, это означало бы повторный ввод кредитов и начало операции if over.

Ответы [ 4 ]

0 голосов
/ 01 февраля 2019

Ну, я мог бы посоветовать вам переосмыслить дизайн.Но это был не твой вопрос - верно?Итак, если вы действительно хотите, то, что вы просили, вот оно, перерыв («исключение для бедняков»):

exitpoint:{

     //your code ...
     break exitpoint;
     //more code
     break exitpoint;
     //....
}

или с некоторым циклом:

exitpoint:
while( ){
    // code....
    for(;;){
        //...
        break exitpoint;
    }
}

Aгораздо лучшим способом обработки ошибок (например, неправильный ввод данных пользователем) являются исключения.Но это был еще не вопрос - не так ли?

0 голосов
/ 01 февраля 2019

do-while конструкция может быть эффективна здесь.

if (studentType.equalsIgnoreCase("R"))
   {

   do {
       System.out.println("Please enter the number of credits that you are 
       taking:");
       creditNumber = input.nextInt();
       if(creditNumber > 18) System.out.println("Too many credits");
   while(creditNumber > 18);
}
0 голосов
/ 01 февраля 2019

Я бы сделал что-то вроде этого:

if (studentType.equalsIgnoreCase("R"))
{

System.out.println("Please enter the number of credits that you are 
taking:");
creditNumber = input.nextInt();

while(creditNumber > 18)
{
    System.out.println("Please re-enter the number of credits that you are 
    taking:");
    creditNumber = input.nextInt();
}

System.out.println("Tuition and fees report for " + name);          
System.out.println("Tuition: "+ tuition);           
System.out.println( "Capital Fee:  \t"+ capitalFee1);           
System.out.println( "Student Activities Fee: \t "+   studentACTFee);            
System.out.println( "Parking Infrastructure Fee: \t " +  parkingFee);           
System.out.println("Tuition & Fees Per Credit: " +  perCreditR);            
System.out.println("X Number of Credits: " + creditNumber);
totalTF = creditNumber * perCreditR;            
System.out.println("Total Tuition and Fees: \t" +  totalTF);
System.out.println("Bodly NOVA");
}

При этом используется оператор while (), который проверяет, больше ли начальный creditNumber больше 18, и постоянно повторяет запрос пользователя на новый ввод.Затем, когда они предоставляют значение, меньшее или равное 18, он выполняет все остальные действия, которые вы хотите сделать.Обратите внимание, я не проверял это, но оно должно работать.

0 голосов
/ 01 февраля 2019

Вы можете попробовать заключить оператор if в цикл do-while:

if (studentType.equalsIgnoreCase("R"))
{
    do{
       System.out.println("Please enter the number of credits that you are taking:");
       creditNumber = input.nextInt();

        if (creditNumber <= 18)
        {
            System.out.println("Tuition and fees report for " + name);          
            System.out.println("Tuition: "+ tuition);           
            System.out.println( "Capital Fee:  \t"+ capitalFee1);           
            System.out.println( "Student Activities Fee: \t "+   studentACTFee);            
            System.out.println( "Parking Infrastructure Fee: \t " +  parkingFee);           
            System.out.println("Tuition & Fees Per Credit: " +  perCreditR);            
            System.out.println("X Number of Credits: " + creditNumber);
            totalTF = creditNumber * perCreditR;            
            System.out.println("Total Tuition and Fees: \t" +  totalTF);
            System.out.println("Bodly NOVA");
        }
        else {System.out.println("Please re-enter credit Number ");}
    }while(creditNumber > 18);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...