为什么这个返回方法不会编译? [英] Why Won't This Return Method Compile?
问题描述
我正在尝试制作一个简单的程序,您可以通过输入命令在四个方向上移动一个空格.这是我的代码:
I am trying to make a simple program where you can move one space in four directions by typing in commands. Here is my code:
public class Map {
public int x;
public int y;
}
和
import java.util.Scanner;
public class Mover {
Scanner input = new Scanner(System.in);
Map map = new Map();
public int move(int x, int y){
map.x = x;
map.y = y;
String direction = input.next();
System.out.println("Where will you move?");
if(direction.equalsIgnoreCase("move right")){
x++;
return x;
}
if(direction.equalsIgnoreCase("move left")){
x--;
return x;
}
if(direction.equalsIgnoreCase("move up")){
y++;
return y;
}
if(direction.equalsIgnoreCase("move down")){
y--;
return y;
}
}
public static void main(String args[]){
Mover mover = new Mover();
}
}
编译器说问题是我需要返回一个 int 值,但很明显我在我所做的每个 if 语句中都有.具体来说,它说在方法的最后返回一个y"值将解决问题.尝试此操作后,错误消失.但是当编译时,程序立即终止.我做错了什么?
The compiler says the problem is that I need to return an int value, but clearly I have in within every if statement I've made. Specifically, it says returning a 'y' value at the very end of the method will solve the problem. After trying this, the errors go away. But when compiled, the program instantly terminates. What am I doing wrong?
推荐答案
如果您的所有条件都为假,则您的方法的执行将到达您的方法的末尾,而不会遇到 return
语句.您必须为这种情况提供返回值.
If all your conditions are false, execution of your method will reach the end of your method without hitting a return
statement. You must provide a return value for that situation.
添加最后一行来完善您的方法:
Add a final line to hone body of your method:
return 0; // for example
Java 方法没有默认"返回值.
Java methods do not have "default" return values.
这篇关于为什么这个返回方法不会编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!