如果给定条件,则if语句不起作用

时间:2019-03-18 16:30:45

标签: java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter price in cents:");
        int money = 100;
        int itemPrice = scan.nextInt();
        money = money - itemPrice;
        int quarter = money / 25;
        money = money % 25;
        int dime = money / 10;
        money = money % 10;
        int nickel = money / 5;
        money = money % 5;

        if (itemPrice < 25 || itemPrice > 100) {
            System.out.println("Invalid price!");
            return;
        } else if ((itemPrice % 5 == 1)) {
            System.out.println("Invalid price!");
            return;
        }

        System.out.println("Your change is " + quarter + " quarters, " + dime + " dimes, and " + nickel + " nickels.");
    }
}

这是我的代码,每当我尝试使else if语句运行时,它就不会。因此,如果我输入54,它仍会进行更改,而不会打印出“无效价格”!

1 个答案:

答案 0 :(得分:3)

如果要检查itemPrice%5!=0是否能被5整除,则需要使用itemPrice%5==1而不是itemPrice