获取用户的更改金额

问题描述 投票:0回答:3

我必须创建一个java程序(不使用if语句),用户输入一个数字,我必须以硬币的形式输出他们的数字:

import java.io.*;
public class ModQuestions
public static void main (String args[]) throws Exception{
BufferedReader buffer = new BufferedReader(newInputStreamReader(System.in));

System.out.println("Enter a number: ");
String s = buffer.readLine();
int n = Integer.parseInt(s);

System.out.println ("That is " + (n / 200) + " toonies.");
n = n % 200;
System.out.println ("That is " + (n / 100) + " loonies.");
n = n % 100;
System.out.println ("That is " + (n / 25) + " quarters.");
n = n % 25;
System.out.println ("That is " + (n / 10) + " dimes.");
n = n % 10;
System.out.println ("That is " + (n / 5) + " nickels.");
n = n % 5;
System.out.println ("That is " + (n) + " pennies.");

到目前为止我有这个,但现在我必须改变我的代码,以便如果答案是0(例如,那是0 toonies)我根本不想打印该行。另外,如果输出是“那是1个Toonies”,我必须说“那是1个toonie”。我一直试图弄清楚如何在不使用if语句的情况下做到这一点,所以如果有人可以提供帮助,那就非常感激:)

java
3个回答
0
投票

欢迎来到Stack Overflow!

在不需要if语句的情况下在Java中使用条件的一种方法是使用Java的三元运算符'?'。

这充当了真/假开关,例如:

int three = 3;
System.out.println((three > 2) ? "greater" : "less");

会打印

greater

因为它充当condition ? true : false

在您的示例中,使用它来检查'toonies'是否大于1,然后如果为true则打印'toonies',如果为false则打印'toonie'。


0
投票

当您使用决策结构,并且不想使用if时,请使用for循环并定义每个硬币的详细信息:

import java.util.Scanner;

public class ModQuestions {

     public static void main(String []args){

        System.out.println("Enter a number: ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        // coinTypes contain the number to be divided for, singular and plural names for each type of coin
        String[][] coinTypes = {{"200", "toony", "toonies"}, {"100", "loony", "loonies"}, {"25", "quarter", "quarters"}, {"10", "dime", "dimes"}, {"5", "nickel", "nickels"}, {"1", "penny", "pennies"}};

        for(String[] coin : coinTypes) {
            int convertedCoin = (n / Integer.parseInt(coin[0]));

            if(convertedCoin > 0) // this is just to check if the value is higher then 0, if not, nothing is printed
            System.out.println("That is " + convertedCoin + " " + (convertedCoin > 1 ? coin[2] : coin[1]));
        }
     }
}

工作示例here


0
投票

您必须根据您的要求操纵条件。您必须更改if条件以捕获所有必需条件并根据该条件编辑响应。

示例场景可以如下识别。

if (n/200 > 0) { // Only continue if there is a chance to represent the amount in `toonies (unit 200s)`
    if(n/200 == 1) { // is only one `toonie` required ?
        System.out.println ("That is " + (n / 200) + " toonie.");
    } else { // more than one `toonie` is required
        System.out.println ("That is " + (n / 200) + " toonies.");
    }
    n = n % 200; // to change `n` to the remainder
} else if (n/100 > 0) {
    .......
} ....... 

推荐问答