1
private void updateDisplay()
{   
    if(hours.getValue() == 0)
    {
        hours.setValue(12);
        displayString = hours.getDisplayValue() + ":" + 
        minutes.getDisplayValue() + " am"; 
    }
    else if(hours.getValue() < 12)
    {
        displayString = hours.getDisplayValue() + ":" + 
        minutes.getDisplayValue() + " am";
    }
    else if(hours.getValue() == 12)
    {
        displayString = hours.getDisplayValue() + ":" + 
        minutes.getDisplayValue() + " pm";
    }
    else if(hours.getValue() < 24)
    { 
        displayString = Integer.toString(hours.getValue() - 12) + ":" +  
        minutes.getDisplayValue() + " pm"; 
    }
}

我只是想用这个方法来改变时钟的显示。我已经工作了几个小时但我被卡住了,因为在这个方法中由于某种原因它一直跳到 else 语句,即使值是输入满足if要求。下面我将显示我正在使用的其他课程的相关部分..编辑现在午夜滚动时不​​会留在上午

public int getValue()
{
    return value;
}

// Return the display value (that is, the current value as a two-digit
// String. If the value is less than ten, it will be padded with a leading
// zero).
public String getDisplayValue()
{
    if(value < 10) {
        return "0" + value;
    }
    else {
        return "" + value;
    }
}

// Set the value of the display to the new specified value. If the new
// value is less than zero or over the limit, do nothing.
public void setValue(int replacementValue)
{
    if((replacementValue >= 0) && (replacementValue < limit)) {
        value = replacementValue;
    }
}
4

1 回答 1

1

我想你错过了一个else

private void updateDisplay()
{
  if(hours.getValue() < 12)
     displayString = hours.getDisplayValue() + ":" +
            minutes.getDisplayValue() + " am";

 [this one] >>>> else if(hours.getValue() >= 12 && hours.getValue() < 25)
     displayString = Integer.toString(hours.getValue() - 12) + ":" + 
            minutes.getDisplayValue() + " pm";

  else {
    hours.setValue(12);
    displayString = hours.getDisplayValue() + ":" + 
                    minutes.getDisplayValue() + " am";
  }
}

添加:

您还可以使用SimpleDateFormat来格式化您的时间。就是这样:

SimpleDateFormat from = new SimpleDateFormat("H");
SimpleDateFormat to = new SimpleDateFormat("h a");

return to.format(from.parse(hours.getValue));

补充2:

如果您需要手动计算,最简单的方法是:

if (hours.getValue() == 0) {
    return "12 am";
} else if (hours.getValue() < 12) {
    return hours.getValue() + " am";
} else if (hours.getValue() == 12) {
    return "12 pm";
} else if (hours.getValue() < 24) {
    return (hours.getValue()-12) + " pm";
} else {
    throw new ParseException("Invalid hours value: "+hours.getValue());
}
于 2012-05-27T07:47:07.393 回答