gpt4 book ai didi

java - 如何将输入的计算存储到内存、输入重复、输入的第一个计算添加到输入的第二个计算等等?

转载 作者:行者123 更新时间:2023-12-02 00:49:34 25 4
gpt4 key购买 nike

我需要一些有关我尝试使用 Java 编写的程序的帮助。

我目前是信息技术专业的新生,对于期末考试,我们必须做某种电力计费程序,我已经完成了一些代码,但它不会按照我想要的方式工作。谁能帮我解决这个问题吗?

程序流程:1)用户输入多个要计算的数字2)程序计算它3)第2步的计算结果存储在某处4)程序询问用户是否要再次输入5)如果用户再次选择输入,则过程重复步骤1到2,并添加到第一个计算中,依此类推

static Scanner console = new Scanner (System.in);
Double loopFor=0.0;
Double w,h,kwh,t;


System.out.print("\nHello and welcome to Pikabill. The electricity bill estimate calculator.");
while(true) {
do {
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w=console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h=console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh=console.nextDouble();

t=(w*h)/1000*kwh;

System.out.print("\nCOST: " + t);
loopFor += t;

System.out.print("\nWould you like to continue? YES [y] No [n]");
String c= console.nextLine();

if(c.equalsIgnoreCase("n")){
break;

}

}
while (loopFor !=0);
}
}

}

不知何故,当我运行这个计算时,计算工作正常,但是当涉及到显示 t(计算)时,它显示“你想继续吗”就好,但“你好,欢迎来到 Pikabill... .” 即使我没有按 y,也会显示在下一行。它也不会将以前的计算添加到新的计算中。

最佳答案

这段代码可以工作。导入java.util.Scanner;

公共(public)课ElectricalBillingProgram{

public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
Double loopFor = 0.0;
Double w, h, kwh, t;
for (int i = 0;; i++)
{
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w = console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h = console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh = console.nextDouble();

t = (w * h) / 1000 * kwh;

System.out.print("\nCOST: " + t);
loopFor += t;

System.out.print("\nWould you like to continue? YES [y] No [n]");
String c = console.next();

if (c.equalsIgnoreCase("n"))
{
break;
}
}

}

}

从代码中观察到的结果:切勿混淆“while”和“doWhile”,如果它让您感到困惑,请使用“for”循环。使用 console.next() 而不是 console.nextLine()。祝学习愉快!

关于java - 如何将输入的计算存储到内存、输入重复、输入的第一个计算添加到输入的第二个计算等等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57871108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com