当获取main()
函数中的输入时......字符串对象instSet
的输入被跳过....有人可以解释为什么会发生这种情况以及如何纠正...现在我只是封闭了我的公共课。如果需要,以后添加其他类...
import java.util.Scanner;
public class MarsRover {
private String inst_set;
private Plateau p;
private Cell currentLocation;
public enum Direction{N,S,E,W}
Direction dir;
public MarsRover(Plateau p1, int x, int y, Direction dir, String instSet) {
p=p1;
inst_set=instSet;
this.dir=dir;
currentLocation=new Cell(x, y);
}
public void executeInst() {
int i = 0;
System.out.println(inst_set.length());
while (i < inst_set.length()) {
//System.out.println("Check");
char inst = inst_set.charAt(i++); //get each inst seperately as a character
if (inst=='M') {
Cell temp=p.getNeighbour(dir, currentLocation);
if (temp != null)
currentLocation=temp;
else
continue;
}
if(inst=='L'||inst=='R'){
dir=setDirection(dir,inst);
}
}
}
private Direction setDirection(Direction dir, char inst) {
if(inst=='L') {
switch (dir) {
case N:
dir = Direction.W;
break;
case W:
dir = Direction.S;
break;
case S:
dir = Direction.E;
break;
case E:
dir = Direction.N;
break;
}
}
else if(inst=='R'){
switch (dir) {
case N:
dir = Direction.E;
break;
case W:
dir = Direction.N;
break;
case S:
dir = Direction.W;
break;
case E:
dir = Direction.S;
break;
}
}
return dir;
}
public static void main(String... a){
Plateau p1=new Plateau();
Scanner in = new Scanner(System.in);
int x,y;
String instSet;
System.out.println("Enter the Initial XLocation:");
x=in.nextInt();
System.out.println("Enter the Initial YLocation:");
y=in.nextInt();
System.out.println("Enter the Instructions");
instSet=in.nextLine();
String dir;
System.out.println("Enter the direction the rover is Headed");
dir=in.nextLine();
MarsRover mr1=new MarsRover(p1,x,y,Direction.valueOf(dir),instSet);
mr1.executeInst();
}
}
答案 0 :(得分:1)
简单解决方案: 你应该简单地致电
instSet=in.next() + in.nextLine();
而不是
in.nextLine()
next()从标准输入返回第一个令牌。 nextLine()返回此标记后的下一行。
另一种解决方案: 每个nextInt()之后的nextLine(),如下所示
System.out.println("Enter the Initial XLocation:");
x=in.nextInt();
in.nextLine();
System.out.println("Enter the Initial YLocation:");
y=in.nextInt();
in.nextLine();
System.out.println("Enter the Instructions\t");
instSet=in.nextLine();
如果您使用Scanner#next ###()(nextLine除外),并且当用户按Enter键时您到达行尾令牌,如果您不处理行尾令牌,它将阻止Scanner对象正常工作。因此,nextInt()不读取并且正在由nextLine()
读取希望它澄清