2016-03-01 3 views
-2

Я пытаюсь подсказать пользователю, правильно ли указана информация, и что программа просто продолжается, вместо повторного запроса пользователя. Я думаю, мне нужно изменить, как я делаю цикл, чтобы сделать какой-то цикл do-while, но я не совсем знаю, что делать.Я не могу правильно получить инструкцию if if.

{ 

    //Here we will set up our method of data entry and decimal format 
    Scanner keyboard = new Scanner(System.in); 
    DecimalFormat eNotation1 = new DecimalFormat("00.00"); 

    //Let's introduce our program to the user 
    System.out.println("Hi, This is a program to calculate quarterly interest growth"); 

    //Here we will prompt the user to enter the amount of quarters 
    System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10"); 
    int quarterNumber = keyboard.nextInt(); 
    if (quarterNumber > 10 || quarterNumber < 0) 
    { 
    System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)"); 
    System.exit(0); 
    } 

    //Here we will prompt the user for the starting balance. 
    System.out.println("What is the starting balance of this account?"); 
    double startingBalance = keyboard.nextDouble(); 

    //Here we will prompt the user for the interest rate 
    System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20."); 
    double interestRate = keyboard.nextDouble(); 
    if (interestRate < 1 || interestRate > 20) 
    { 
    System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)"); 
    System.exit(0); 
    } 

    //Here we will double check with the user that the info is correct. 
    System.out.println("The amount of quarters you would like displayed is " + quarterNumber); 
    System.out.println("The starting balance you would like to work with is " + startingBalance); 
    System.out.println("The interest rate in your area is " + interestRate); 
    System.out.println("Is this information correct?"); 
    keyboard.nextLine(); 
    String answer = keyboard.nextLine(); 
    System.out.println(""); 

    //We will have them enter the information again if the answer is no or No 
    if (answer == "no" || answer == "No") 
    { 
    //Here we will prompt the user to enter the amount of quarters 
    System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10"); 
    keyboard.nextInt(); 
    quarterNumber = keyboard.nextInt(); 

    //Here we will prompt the user for the starting balance. 
    System.out.println("What is the starting balance of this account?"); 
    keyboard.nextDouble(); 
    startingBalance = keyboard.nextDouble(); 

    //Here we will prompt the user for the interest rate 
    System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20."); 
    keyboard.nextDouble(); 
    interestRate = keyboard.nextDouble(); 
    } 

    //Next we will proceed with the calculation if the information is indeed correct 
    double endingBalance = startingBalance + (startingBalance * (interestRate/100 * .25)); 
    double interestEarned = endingBalance - startingBalance; 

    //Now we will output the information 
    for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate/100 * .25)), interestEarned = endingBalance - startingBalance) 
    { 
    System.out.println("Quarter Number      Starting Balance      Interest Earned       Ending Balance "); 
    System.out.println(qn + "         " + eNotation1.format(startingBalance) + "        " + eNotation1.format(interestEarned) + "          " + eNotation1.format(endingBalance) + " ");     
    } 


} 

}

+0

Вы должны сообщить нам, где именно ваша ошибка. Кроме того, вы не сказали нам, что представляет собой клавиатура. Кроме того, упростите свою проблему в новом проекте или что-то еще, так что вам легче понять вашу проблему. – aeee98

+0

Хорошо, это мой первый семестр программирования, как вы, вероятно, можете сказать, не привык задавать эти вопросы. Вот более подробно, я сначала предлагаю пользователю ввести 3 переменные: «quarterNumber», «startBalance» и «процентная ставка». Затем я пытаюсь спросить их, правильна ли информация. Я хотел бы, чтобы опрос начинался, если пользователь вводит: «нет» или «нет». В настоящее время, когда я запускаю программу, я набираю «no», и она не запрашивает меня для ввода снова, как было разработано. – Kevin

ответ

0

Я, вероятно, понял, в чем проблема.

Пример фрагмента кода: (Обратите внимание, что я делаю без фактического редактора Java так просто справиться с любой недостающий синтаксис

//Here we will prompt the user to enter the amount of quarters 
int quarters = 0; 
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10"); 
do 
{ 
quarters = keyboard.nextInt(); 
if (quarters <= 0 || quarters >= 10) 
{ 
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)"); 
} 
} 
while (quarters <= 0 || quarters >= 10) 

Идея для рекурсивного запроса Приложение первым предложит пользователю ввести в результат. , а затем вы обрабатываете количество. Таким образом, вы должны обрабатывать подсказку в цикле do-while. Предполагая, что вы не хотите повторять один и тот же старый текст, вы можете делать то, что я сделал (что на мой взгляд намного чище) .

EDIT: Предполагая, что вы хотите обрабатывать все повторение приложения. (или лучше использовать различные методы для более чистого управления и обрабатывать что-то вроде этого.

int quarters; 
double balance; 
//TODO : Add all other required variables 
string verification; 

do 
{ 
quarters = getNumberOfQuartersFromUser(); 
balance = getStartingBalance(); 
... //TODO : all the other methods 
//verification 
System.out.println("Is this accepted?"); 
verification = keyboard.nextString(); 
//Handle verfication if it is no or No 
if (verification == null || verification == "No" || verification == "no") 
{ 
System.out.println("Starting from the beginning again"); 
} 
} 
while (verification == null || verification == "No" || verification == "no") 
//out of loop, so handle calculation. 
... 

и метод фрагмент кода

private int getNumberOfQuartersFromUser() 
{ 
int quarters = 0; 
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10"); 
do 
{ 
quarters = keyboard.nextInt(); 
if (quarters <= 0 || quarters >= 10) 
{ 
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)"); 
} 
} 
while (quarters <= 0 || quarters >= 10) 
return quarters; 
} 
+0

Да, это прекрасно и намного лучше! Спасибо вам большое, сэр! – Kevin

+0

upvote и правильный ответ будет хорошей оценкой :) – aeee98

0

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

+0

Привет, спасибо за помощь. Я не совсем уверен, когда буду писать свои высказывания Else. Я бы сказал что-то вроде, если ответить == да или Да, затем продолжить. Else reprompt пользователь для ввода? – Kevin

+0

если (условие) { (действие) } еще { (действие) } –

+0

помните, что вы могли бы выполнить вложенным, если заявление, чтобы избежать путаницы в коде. если ваше условие выполнено, сделайте это, если не поместите «else» для другого действия. и если у вас есть другое условие, вы можете поместить else if (condition) {}. –

0
{ 

//Here we will set up our method of data entry and decimal format 
Scanner keyboard = new Scanner(System.in); 
DecimalFormat eNotation1 = new DecimalFormat("00.00"); 

//Let's introduce our program to the user 
System.out.println("Hi, This is a program to calculate quarterly interest growth"); 

//Here we will prompt the user to enter the amount of quarters 
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10"); 
int quarterNumber = keyboard.nextInt(); 

//Here you had started your condition I'll try to make it nested if statement 
if (quarterNumber > 10 || quarterNumber < 0) 
//if the condition is true perform this 
{ 
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)"); 
System.exit(0); 
} 
else{ 
//if false conditions inside else statement should be performed 

//Here we will prompt the user for the starting balance. 
System.out.println("What is the starting balance of this account?"); 
double startingBalance = keyboard.nextDouble(); 

//Here we will prompt the user for the interest rate 
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20."); 
double interestRate = keyboard.nextDouble(); 

//you could put another if statement inside if statement which is known as nested if statement. 
if (interestRate < 1 || interestRate > 20) 
{ 
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)"); 
System.exit(0); 
} 
else{ 
//like before you should enclose this to else to avoid confusion 

//Here we will double check with the user that the info is correct. 
System.out.println("The amount of quarters you would like displayed is " + quarterNumber); 
System.out.println("The starting balance you would like to work with is " + startingBalance); 
System.out.println("The interest rate in your area is " + interestRate); 
System.out.println("Is this information correct?"); 
keyboard.nextLine(); 
String answer = keyboard.nextLine(); 
System.out.println(""); 

//We will have them enter the information again if the answer is no or No 
if (answer == "no" || answer == "No") 
{ 
//Here we will prompt the user to enter the amount of quarters 
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10"); 
keyboard.nextInt(); 
quarterNumber = keyboard.nextInt(); 

//Here we will prompt the user for the starting balance. 
System.out.println("What is the starting balance of this account?"); 
keyboard.nextDouble(); 
startingBalance = keyboard.nextDouble(); 

//Here we will prompt the user for the interest rate 
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20."); 
keyboard.nextDouble(); 
interestRate = keyboard.nextDouble(); 
} 

//Next we will proceed with the calculation if the information is indeed correct 
double endingBalance = startingBalance + (startingBalance * (interestRate/100 * .25)); 
double interestEarned = endingBalance - startingBalance; 

//Now we will output the information 
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate/100 * .25)), interestEarned = endingBalance - startingBalance) 
{ 
System.out.println("Quarter Number      Starting Balance      Interest Earned       Ending Balance "); 
System.out.println(qn + "         " + eNotation1.format(startingBalance) + "        " + eNotation1.format(interestEarned) + "          " + eNotation1.format(endingBalance) + " ");     
} 
} 
} 
} 

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

Смежные вопросы