我在编写这段代码时,不禁想知道是否可以在三元函数中使用else语句。
我想打印1作为第1,2作为第2,3作为第3,4-10作为4-10。
这是有可能做到所有的三元还是不可能的?
while (gradeCounter <= 10){
System.out.printf(gradeCounter==1?"Enter %dst grade: ":"Enter %dth grade : ", gradeCounter);
//how can I do "else if" in ternary function
int grade = input.nextInt();
total = total + grade;
gradeCounter = gradeCounter + 1;
}
发布于 2016-05-06 16:41:47
如果您的成绩介于1到10之间,那么您可以使用sufixArray,对于大于10的数字,您需要将x1、x2和x3提升到"th"-cardinal结束。
示例:
String[] cardinalSufixes = new String[]{ "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
for (int i = 1; i <= 10; i++) {
System.out.printf("Enter %d%s grade: \n", i, cardinalSufixes[i % 10]);
}
使用此操作而不是嵌套三元运算符的优点是cyclomatic complexity,如果后者希望更改嵌套代码中的任何逻辑条件,则破坏代码的概率要高于仅使用模操作时的概率。
片段将打印出来:
进入1年级:进入2年级:进入3年级:进入4年级:进入5年级:进入6年级:进入7年级:进入8年级:进入9年级:进入10年级:
这是你要找的基本秩序..。
https://stackoverflow.com/questions/37077224
复制相似问题