簡體   English   中英

方法中的Java邏輯問題

[英]java logic issue in method

當我嘗試運行此代碼時,它將不斷返回錯誤的值,並且我無法弄清楚哪里出了問題。 我將10添加到catUp后,它可以正確打印,但是當我檢查該值是否大於199時,由於某種原因它會通過該if語句。 同樣,當我在upCategory方法的末尾將其打印出來時,它的值為1,但是當我在主窗口中打印時,它的值為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成為一個正常的塊,並始終執行。

要將大括號中的塊附加到if語句,請刪除分號:

if (catUp > 199.0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM