[英]Creating a string with nested if statements in java
我目前正在研究一个项目,以改善商店的现金管理。 在程序的某个时刻,我有一个字符串,该字符串根据晚上开出的哪些账单和多少张账单创建。 我最初写了一个嵌套的if语句块来使它起作用,但是它不起作用,我明白了为什么。 这是我写的嵌套语句:
//this nested block does not work but I want to try and find a way to make it work.
/*if(hundred == 0){
if(fifty == 0){
if(twenty == 0){
if(ten == 0){
if(five == 0){
dropString = String.format("Drop(%d-$1's)%s", one, initials);
}
else
dropString = String.format("Drop(%d-$5's, %d-$1's)%s", five, one, initials);
}
else dropString = String.format("Drop(%d-$10's, %d-$5's, %d-$1's)%s", ten, five, one, initials);
}
else dropString = String.format("Drop(%d-$20's, %d-$10's, %d-$5's, %d-$1's)%s", twenty, ten, five, one, initials);
}
else dropString = String.format("Drop(%d-$50's, %d-$20's, %d-$10's, %d-$5's, %d-$1's)%s", fifty, twenty, ten, five, one, initials);
}
else dropString = String.format("Drop(%d-$100's, %d-$50's, %d-$20's, %d-$10's, %d-$5's, %d-$1's)%s", hundred, fifty, twenty, ten, five, one, initials);
我希望字符串仅包含大于零的值,您可以看到使用此方法显然将不起作用,因为它将在一个语句大于零之后包含所有块。 我已经找到了适合我想要的东西,但是如果变量“百”为零,那并不是最好的选择。 这是我想出的可行的方法:
if(hundred != 0)
dropString += String.format("%d-$100's", hundred);
if(fifty != 0)
dropString += String.format(", %d-$50's", fifty);
if(twenty != 0)
dropString += String.format(", %d-$20's", twenty);
if(ten != 0)
dropString += String.format(", %d-$10's", ten);
if(five != 0)
dropString += String.format(", %d-$5's", five);
if(one != 0)
dropString += String.format(", %d-$1's", one);
dropString += String.format(")%s", initials);
当“百”等于零时,字符串类似于“ Drop(,16- $ 20's)RE”。我的问题是,有没有办法使用嵌套语句或删除前导的好方法”, ”“百”何时为零? (我想要一种不涉及等于或大于零的值的每个可能组合的if语句的方法)
尝试这个:
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
List<Integer> asList = new ArrayList<Integer>(Arrays.asList(100, 50, 20, 5, 1));
int sum = 1284;
while (!asList.isEmpty()) {
int op = asList.remove(0);
int result = sum / op;
if (result > 0) {
sb.append(String.format("%d-$%d's,", result, op));
}
sum -= result * op;
}
if (sb.length() > 0) {
sb.replace(sb.length() - 1, sb.length(), "");
}
System.out.println("Drop(" + sb + ")RE");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.