[英]Obtaining user's amount in change
我必须创建一个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桃花心木),我根本就不想打印该行。 另外,如果输出为“ That is 1 Toonies”,则必须说“ That is 1 toonie”。 我一直在尝试找出不使用if语句的情况下如何执行此操作,因此如果有人可以提供帮助,将不胜感激:)
欢迎使用Stack Overflow!
在Java中使用条件而不需要if语句的一种方法是使用Java的三元运算符 '?'。
这充当一个true / false开关,例如:
int three = 3;
System.out.println((three > 2) ? "greater" : "less");
将打印
greater
作为condition ? true : false
condition ? true : false
在您的示例中,使用它来检查“ toonies”是否大于1,然后打印“ toonies”(如果为true)或“ toonie”(如果为false)。
当您使用决策结构且不想使用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]));
}
}
}
这里的工作示例。
您必须根据您的要求操纵条件。 您必须更改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) {
.......
} .......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.