#java #while-loop
Вопрос:
Я не совсем понимаю, как сделать так, чтобы мой базовый финансовый калькулятор мог запускать новый набор чисел, не закрывая программу. То, что у меня сейчас есть, позволяет мне запустить один набор чисел, и когда я перейду к «Вы хотели бы продолжить?», когда я нажму 1, он просто напечатает «Вы хотели бы продолжить?». сколько бы раз я ни нажимал 1. Вот что у меня есть до сих пор:
package Register;
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 night2;
{
System.out.println("Electricity Bill: $" total);
}
System.out.println("");
boolean keepLooping = true;
while (keepLooping) {
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}
Ответ №1:
Вы использовали цикл while только для запроса операторов выбора. Поэтому используйте цикл while в начале основного метода, как показано ниже:
import java.util.Scanner;
public class Register{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
boolean keepLooping = true;
while(keepLooping) {
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 night2;
System.out.println("Electricity Bill: $" total);
System.out.println("");
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}