gpt4 book ai didi

java方法中的逻辑问题

转载 作者:行者123 更新时间:2023-12-01 18:43:21 28 4
gpt4 key购买 nike

当我尝试运行此代码时,它不断返回错误的值,并且我无法弄清楚哪里出了问题。在我将 10 添加到 catUp 后,它会正确打印出来,但是当我检查相同的值是否大于 199 时,由于某种原因,它会通过该 if 语句。另外,当我在 upCategory 方法末尾打印它时,它给出的值是 1,但是当我在 main 中打印它时,它给出的值是 3。

 public void upCategory()
{
double catUp = radioXM.getCurrentStaion();
catUp += 10;
System.out.println(catUp);
if (catUp > 199.0);
{
catUp = 1;
radioXM.setCurrentStation(catUp);
System.out.println(catUp);
}
radioXM.setCurrentStation(catUp);
System.out.println(catUp);
}
public static void main (String [] args) {
AutoRadioSystem c = new AutoRadioSystem();
c.selectRadio();
double b = c.getCurrentStation();
System.out.println(b);

// this changes the radio to XM
c.selectRadio();
double d = c.getCurrentStation();
System.out.println(d);

//this is suppose to change the station up by 10 but gives incorrect value
c.upCategory();
double f = c.getCurrentStation();
System.out.println(f);
}

附带的附加代码...

public abstract class Radio 
{
double currentStation;

RadioSelectionBar radioSelectionBar;
public Radio()
{
this.currentStation = getMin_Station();
}
public abstract double getMax_Station();
public abstract double getMin_Station();
public abstract double getIncrement();
public void up()
{

}
public void down()
{

}
public double getCurrentStaion()
{
return this.currentStation;
}
public void setCurrentStation(double freq)
{
currentStation += freq;
}
public void setStation(int buttonNumber, double station)
{
}
public double getStation(int buttonNumber)
{
return 0.0;
}
public String toString()
{
String message = ("" + currentStation);
return message;
}
public boolean equals (Object o)
{
if (o == null)
return false;
if (! (o instanceof Radio))
return false;
Radio other = (Radio) o;
return this.currentStation == other.currentStation;
}

public class XMRadio extends Radio
{
private static final double Max_Station = 199;
private static final double Min_Station = 1;
private static final double Increment = 1;
public XMRadio()
{
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("XM "+ currentStation );
return message;
}
}

最佳答案

这一行是问题所在:

if (catUp > 199.0);

Java将分号视为if语句的主体,if下面的大括号中的 block 成为普通 block ,并且始终被执行。

要将大括号中的 block 附加到 if 语句,请删除分号:

if (catUp > 199.0)

关于java方法中的逻辑问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994193/

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