我完成了这项任务。看着它,我觉得括号和if else语句的一切都很好。但是,错误表示"缺少return statement}"
_____________________________________________________________________ ^
public class CompareNums {
// TODO - write your code below this comment.
// The method you define will return one of three possible strings:
// - "less than": if the first parameter is less than the second
// - "equal to": if the first parameter is equal to the second
// - "greater than": if the first parameter is greater than the second
// Make sure you return _exactly_ the above strings
public static String comparison(int first, int second) {
if (first<second) {
return "less than";
} else if (first==second) {
return "equal to";
} else if (first>second) {
return "greater than";
}
}
// DO NOT MODIFY main!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first integer: ");
int first = input.nextInt();
System.out.print("Enter second integer: ");
int second = input.nextInt();
System.out.println("The first integer is " +
comparison(first, second) +
" the second integer.");
}
}
答案 0 :(得分:1)
如果您在函数内使用返回,则需要使用if
结束else
语句。错误基本上是说如果没有满足这些条件,仍然需要返回一些内容。使用您的示例,您可以这样说:
public static String comparison(int first, int second) {
if (first<second) {
return "less than";
} else if (first>second) {
return "greater than";
} else {
return "equal to";
}
}
你可以假设,如果第一个不小于或大于第二个,则它等于。
答案 1 :(得分:0)
if (first<second) {
return "less than";
} else if (first==second) {
return "equal to";
} else if (first>second) {
return "greater than";
}
最后else if
是多余的,是问题的真正原因。自然如果以上两个条件都是假的,那么first
将大于second
。只需使用else
代替else if
。
if (first<second) {
return "less than";
} else if (first==second) {
return "equal to";
} else {
return "greater than";
}