gpt4 book ai didi

java - 程序运行,但无论输入如何,第二个循环都会结束

转载 作者:行者123 更新时间:2023-12-02 05:51:14 25 4
gpt4 key购买 nike

我对java真的很陌生,我很难找到我在这里做错的地方,这个程序是询问销售量,然后不管销售量有多少,都得到平均值,这部分似乎工作得很好。当它询问运费时,它接受第一个输入,但无论您回复 y 还是 n,它都会结束,程序结束,我是否错过了一些非常明显的东西? (我也尝试看看其他人如何使其更具可读性,很抱歉我不知道我在做什么,很抱歉。)

尝试更改它,但它只是犯了错误,我不知道如何解决自己,因为我是新手,这是我第一次尝试学习 java,我的学校要求我们使用 NetBeans(在我的例子中是 10.0)

import java.util.*;

public class JavaApplication3
{ //these ones are the attributes. private String Sales1,2,3;
public static boolean b_repeat = true;
private double Sales1;
private double Sales2;
private double Sales3;

//this is a constructor of 2 parameters for Cales class.
public JavaApplication3(double Sales1, double Sales2, double Sales3)
{
this.Sales1 = Sales1;
this.Sales2 = Sales2;
this.Sales3 = Sales3;
}

public static void main(String args[])
{
double avg = computeAverageSales();
System.out.println(" Average of Sales :" + avg);
if (avg > 200) {
System.out.println(" Product has produced a significant amount of revenue!");
}
double chr = computeShippingCharges();
System.out.println(" Total shipping charge :" + chr);
}

public static double computeAverageSales()
{
double avgSales, salesIn, total = 0;
int cnt = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Input Sales");
double sales = sc.nextDouble();
total = total + sales;
cnt++;
System.out.println("Would you like to keep adding Sales? (y/n)");

String repeatLoop = sc.next();
if (repeatLoop.toLowerCase().equals("n"))
b_repeat = false;
} while (b_repeat);

System.out.println(); //Space seperator
avgSales = total / cnt;
return (avgSales);
}

public static double computeShippingCharges()
{
double avgShipping, shippingIn, total = 0;
int cnt = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Input Shipping cost");
double shipping = sc.nextDouble();
total = total + shipping;
cnt++;
System.out.println("Would you like to keep adding Shipping costs? (y/n)");

String repeatLoop = sc.next();
if (repeatLoop.toLowerCase().equals("n"))
b_repeat = false;
} while (b_repeat);

System.out.println(); //Space seperator
avgShipping = total;
return (avgShipping);

}

public double getSales1()
{
return this.Sales1;
}

public void setSales1(double sales)
{
this.Sales1 = sales;
}

public double getSales2()
{
return this.Sales2;
}

public void setSales2(double sales)
{
this.Sales2 = sales;
}

public double getSales3()
{
return this.Sales3;
}

public void setSales3(double sales)
{
this.Sales3 = sales;
}
}

它应该接受任意数量的销售或运输输入,但无论您如何回应,运输都只允许一项输入

System.out.println("您想继续添加运费吗?(y/n)");

与,所以这是我的问题

最佳答案

简单来说,变量b_repeat是在使用它的方法之外定义的,并且每次都会重用。因此,第一次调用 computeAverageSalescomputeShippingCharges 时,它可以正常工作,但下一次 b_repeat 已被设置为 false之前的通话。尝试将 boolean b_repeat = true; 移动到每个函数中,看看会发生什么。

关于java - 程序运行,但无论输入如何,第二个循环都会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56046460/

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