Java-自动售货机,可';我不收便士

Java-自动售货机,可';我不收便士,java,Java,因此,我正在从事一个java项目,该项目涉及创建一台根据温度调整价格的汽水机。我似乎不知道如何确保机器在接受用户付款时不接受便士 我觉得我的代码编得太多了,但我已经束手无策了,因为我不知道如何不接受便士 import java.util.*; import java.text.*; public class SodaMachine extends SodaTester { public static void main(String[] args) { doubl

因此,我正在从事一个java项目,该项目涉及创建一台根据温度调整价格的汽水机。我似乎不知道如何确保机器在接受用户付款时不接受便士

我觉得我的代码编得太多了,但我已经束手无策了,因为我不知道如何不接受便士

import java.util.*;
import java.text.*;
public class SodaMachine extends SodaTester
{
    public static void main(String[] args)
    {
        double temp;
        double money;
        double change;
        double price1 = .50;
        double price2 = .55;
        double price3 = .60;
        double price4 = .65;
        double price5 = .75;
        double price6 = .80;
        double price7 = .85;
        double price8 = .90;
        double price9 = 1.00;

        System.out.println("Hi there! Please enter the temperature in Farenheit:");
        Scanner scan = new Scanner(System.in);
        temp = scan.nextDouble();
        DecimalFormat fmt = new DecimalFormat("0.#");

        NumberFormat fmt2 = NumberFormat.getCurrencyInstance();

        if (temp < 40 || temp > 120)
        {
            System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
            while (temp < 40 || temp > 120)
            {
                temp = scan.nextDouble();
                System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
                System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
            }
        }

        if(temp < 50 && temp >= 40)
        {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price1));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price1)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price1));
                money = scan.nextDouble();
            }
            change = money - price1;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp >= 50 && temp <= 60) {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price2));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price2)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price2));
                money = scan.nextDouble();
            }
            change = money - price2;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp > 60 && temp <= 65) { 
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price3));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price3)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price3));
                money = scan.nextDouble();
            }
            change = money - price3;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp > 65 && temp <= 70) {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price4));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price4)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price4));
                money = scan.nextDouble();
            }
            change = money - price4;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp > 70 && temp <= 75) {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price5));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price5)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price5));
                money = scan.nextDouble();
            }
            change = money - price5;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp > 75 && temp <= 80) {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price6));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price6)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price6));
                money = scan.nextDouble();
            }
            change = money - price6;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp > 80 && temp <= 85) {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price7));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price7)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price7));
                money = scan.nextDouble();
            }
            change = money - price7;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp > 85 && temp <= 90) {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price8));

             System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price8)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price8));
                money = scan.nextDouble();
            }
            change = money - price8;
            System.out.println("Your Change is: " + fmt2.format(change));
        }else if (temp > 90 && temp <= 120) {
            System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
            System.out.println("The price is: " + fmt2.format(price9));

            System.out.println("Please insert amount of payment: ");
            money = scan.nextDouble();
            while (money < price9)
            {
                System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price9));
                money = scan.nextDouble();
            }
            change = money - price9;
            System.out.println("Your Change is: " + fmt2.format(change));
        }
    }






















}
import java.util.*;
导入java.text.*;
公共级SodaMachine扩展SodaTester
{
公共静态void main(字符串[]args)
{
双温;
双倍货币;
双重变化;
双倍价格1=0.50;
双倍价格2=0.55;
双倍价格3=0.60;
双倍价格4=0.65;
双倍价格5=0.75;
双倍价格6=0.80;
双倍价格7=0.85;
双倍价格8=0.90;
双倍价格9=1.00;
System.out.println(“您好!请在Farenheit中输入温度:”);
扫描仪扫描=新扫描仪(System.in);
temp=scan.nextDouble();
DecimalFormat fmt=新的DecimalFormat(“0.#”);
NumberFormat fmt2=NumberFormat.getCurrencyInstance();
如果(温度<40 | |温度>120)
{
System.out.println(“无效输入。温度应在40到120华氏度之间”);
而(温度<40 | |温度>120)
{
temp=scan.nextDouble();
System.out.println(“四舍五入温度,单位为华氏度:“+fmt.format(temp));
System.out.println(“无效输入。温度应在40到120华氏度之间”);
}
}
如果(温度<50和温度>=40)
{
System.out.println(“四舍五入温度,单位为华氏度:“+fmt.format(temp));
System.out.println(“价格为:+fmt2.format(price1));
System.out.println(“请插入付款金额:”);
money=scan.nextDouble();
而(货币<价格1)
{
System.out.println(“无效输入,请重试。您的总数为:”+fmt2.format(price1));
money=scan.nextDouble();
}
变化=货币-价格1;
System.out.println(“您的更改是:“+fmt2.format(Change));

}否则,如果(temp>=50&&temp 60&&temp 65&&temp 70&&temp 75&&temp 80&&temp 85&&temp 90&&temp您的代码可以简化很多,但我将重点关注当前的问题

我将创建一个函数来获取用户输入,确保它不包含便士:

double getMoney(String prompt, Scanner scan)
{
    double money = 0;
    while(true) {   // Loop until proper input
        System.out.println(prompt);
        money = scan.nextDouble();
        // There are a few ways to determine if it has pennies.
        // I will convert to int and check if it is divisible
        // by 10 or 5
        int i = (int)Math.round(money * 100);  // Convert to pennies
        if (0 == i % 5) {
            // It's ok, return
            return money;
        }
    }
}

旁注:对货币使用浮点是不好的做法。浮点会引入舍入错误。最好使用整数,并使用最小面额存储值。在这种情况下,使用便士。

您的代码可以简化很多,但我将重点讨论当前的问题

我将创建一个函数来获取用户输入,确保它不包含便士:

double getMoney(String prompt, Scanner scan)
{
    double money = 0;
    while(true) {   // Loop until proper input
        System.out.println(prompt);
        money = scan.nextDouble();
        // There are a few ways to determine if it has pennies.
        // I will convert to int and check if it is divisible
        // by 10 or 5
        int i = (int)Math.round(money * 100);  // Convert to pennies
        if (0 == i % 5) {
            // It's ok, return
            return money;
        }
    }
}

旁注:对货币使用浮点是不好的做法。浮点会引入舍入错误。最好使用整数,并使用最小面额存储值。在这种情况下,是便士。

我不会详细介绍您当前的代码,但您基本上希望检查您是否从用户mod读取了十进制值ulo-
0.05
等于
0
(因此它没有余数)。其中的一个问题是,当您使用
double
时,浮点精度可能会干扰检查,这就是为什么您总是希望使用
java.math.bigdecime
进行货币计算的原因

这里有一个例子:

BigDecimal input = new BigDecimal(scanner.next());
if(input.remainder(new BigDecimal("0.05")).compareTo(BigDecimal.ZERO) == 0){
  System.out.println("Input "+input+" is valid!");
} else{
  System.out.println("Input "+input+" is not valid!");
}
对于输入
“1”
“1.00”
“1.05”
“4.35”
“1.01”
“3.21”
“4.68”
,它将输出以下内容:

Input 1 is valid!
Input 1.00 is valid!
Input 1.05 is valid!
Input 4.35 is valid!
Input 1.01 is not valid!
Input 3.21 is not valid!
Input 4.68 is not valid!
Input 100 is valid!
Input 105 is valid!
Input 435 is valid!
Input 101 is not valid!
Input 321 is not valid!
Input 468 is not valid!


由于
BigDecimal
可能会让新Java用户感到非常困惑,因此您可以让用户以美分(整数)为单位输入金额,在这种情况下,它可以是这样的:

int input = scanner.nextInt();
if(input % 5 == 0){
  System.out.println("Input "+input+" is valid!");
} else{
  System.out.println("Input "+input+" is not valid!");
}
对于输入
“100”
“105”
“435”
“101”
“321”
“468”
,它将输出以下内容:

Input 1 is valid!
Input 1.00 is valid!
Input 1.05 is valid!
Input 4.35 is valid!
Input 1.01 is not valid!
Input 3.21 is not valid!
Input 4.68 is not valid!
Input 100 is valid!
Input 105 is valid!
Input 435 is valid!
Input 101 is not valid!
Input 321 is not valid!
Input 468 is not valid!


编辑:因为我有一些时间,我用可重用的方法重新编写了您的解决方案

请仔细看看我做了什么,如果您对特定部分有任何疑问,请告诉我。它现在使用递归方法,直到用户输入有效的输入。方法中的
布尔showMessage
参数仅显示一次
“Please enter X”
消息

import java.lang.IllegalArgumentException;
import java.lang.NumberFormatException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SodaMachine{ 
  private static final String currencySymbol = "$";
  private static final BigDecimal roundOn = new BigDecimal("0.05");
  private Scanner scanner;
  private NumberFormat currencyFormat;

  public SodaMachine(){
    scanner = new Scanner(System.in);
    currencyFormat = NumberFormat.getCurrencyInstance();
  }

  public static void main(String[] args){
    SodaMachine sodaMachine = new SodaMachine();
    double farenheitInput = sodaMachine.enterFarenheit(true);
    System.out.println("The temperature in degrees Farenheit you've entered is: " + farenheitInput);

    BigDecimal price = sodaMachine.determinePrice(farenheitInput);
    System.out.println("The price is: " + sodaMachine.currencyFormat.format(price));

    BigDecimal payment = sodaMachine.enterPayment(price, true);

    BigDecimal change = payment.subtract(price);
    System.out.println("Your change is: " + sodaMachine.currencyFormat.format(change));
  }

  private double enterFarenheit(boolean showMessage){
    if(showMessage){
      System.out.println("Hi there! Please enter the temperature in Farenheit:");
    }

    double farenheitInput;
    try{
      farenheitInput = scanner.nextDouble();
    } catch(InputMismatchException ex){
      scanner.nextLine(); // Get rid of the invalid user-input
      System.out.println("The value you've entered is not a valid. The input should be a decimal input. Please try again.");
      return enterFarenheit(false);
    }

    if(farenheitInput < 40 | farenheitInput > 120){
      System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
      return enterFarenheit(false);
    }

    return farenheitInput;
  }

  private BigDecimal determinePrice(double farenheit){
    String strPrice;
    // Temperature is in the range [40, 50):
    if(farenheit >= 40 && farenheit < 50){
      strPrice = "0.50";
    }
    // Temperature is in the range [50, 60]:
    else if(farenheit >= 50 && farenheit <=60){
      strPrice = "0.55";
    }
    // Temperature is in the range (60, 65]:
    else if(farenheit > 60 && farenheit <= 65){
      strPrice = "0.60";
    }
    // Temperature is in the range (65, 70]:
    else if(farenheit > 65 && farenheit <= 70){
      strPrice = "0.65";
    }
    // Temperature is in the range (70, 75]:
    else if(farenheit > 70 && farenheit <= 75){
      strPrice = "0.75";
    }
    // Temperature is in the range (75, 80]:
    else if(farenheit > 75 && farenheit <= 80){
      strPrice = "0.80";
    }
    // Temperature is in the range (80, 85]:
    else if(farenheit > 80 && farenheit <= 85){
      strPrice = "0.85";
    }
    // Temperature is in the range (85, 90]:
    else if(farenheit > 85 && farenheit <= 90){
      strPrice = "0.90";
    }
    // Temperature is in the range (90, 120]:
    else if(farenheit > 90 && farenheit <= 120){
      strPrice = "1.00";
    }
    // Invalid temperature range:
    else{
      // Since we already validated the input-range, it should never go here,
      // but added it just in case.
      throw new IllegalArgumentException("The temperature must be in the range [40, 120]!");
    }
    return new BigDecimal(strPrice);
  }

  private BigDecimal enterPayment(BigDecimal price, boolean showMessage){
    if(showMessage){
      System.out.println("Please enter amount of payment: ");
    }

    String userInput = scanner.next();
    // Remove the optional currency symbol from the user input
    userInput = userInput.replace(currencySymbol, "");

    BigDecimal paymentInput;
    try{
      paymentInput = new BigDecimal(userInput);
    } catch(NumberFormatException ex){
      scanner.nextLine(); // Get rid of the invalid user-input
      System.out.println("The value you've entered is not a valid. The input should be a price input. Please try again.");
      return enterPayment(price, false);
    }

    if(paymentInput.compareTo(price) < 0){
      System.out.println("Your payment of " + currencyFormat.format(paymentInput) + " is too low. Please try again. The total price is: " + currencyFormat.format(price));
      return enterPayment(price, false);
    }

    if(paymentInput.remainder(roundOn).compareTo(BigDecimal.ZERO) != 0){
      System.out.println("Your payment should be rounded to " + currencyFormat.format(roundOn) + ". Please try again.");
      return enterPayment(price, false);
    }

    return paymentInput;
  }
}
import java.lang.IllegalArgumentException;
导入java.lang.NumberFormatException;
导入java.math.BigDecimal;
导入java.text.NumberFormat;
导入java.util.InputMismatchException;
导入java.util.Scanner;
公共类SodaMachine{
私有静态最终字符串currencySymbol=“$”;
专用静态最终BigDecimal循环=新的BigDecimal(“0.05”);
私人扫描仪;
专用数字格式(currencyFormat);
公共苏打机(){
扫描仪=新扫描仪(System.in);
currencyFormat=NumberFormat.getCurrencyInstance();
}
公共静态void main(字符串[]args){
SodaMachine SodaMachine=新的SodaMachine();
double Farenheit输入=sodaMachine.enterFarenheit(真);
System.out.println(“您输入的温度单位为:“+Farenheit输入”);
BigDecimal价格=sodaMachine.determinePrice(费恩海输入);
System.out.println(“价格为:+sodaMachine.currencyFormat.format(价格));
BigDecimal payment=sodaMachine.enterPayment(价格,true);
BigDecimal变更=付款。减去(价格);
System.out.println(“您的更改是:+sodaMachine.currencyFormat.format(更改));
}
专用双输入FarenHeit(布尔显示消息){
如果(显示消息){
System.out.println(“您好!请在Farenheit中输入温度:”);
}
双法伦海蒂输入;
tr