补充:
关于nextLine()与next()的区别:
例如:
1.next()
int t = input.nextInt();
String s = input.nextLine();
System.out.println(t + " " + s);
2.next()
int t = input.nextInt();
input.next();
String s = input.nextLine();
System.out.println(t + " " + s);
3.nextLine()(只有这个是正确的)
int t = input.nextInt();
input.nextLine();
String s = input.nextLine();
System.out.println(t + " " + s);
或者
int t = input.nextInt();
String s = input.next();
System.out.println(t + " " + s);
WA代码:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
// input.next();//吃掉空格 next()与nextLine()区别 ???
int i, j;
int L1, R1;
int sum;
String s;
char direction;
for (i = 1; i <= t; i++) {// 表示t次操作
direction='N';
L1 = R1 = 0;
sum=0;
int x = 0, y = 0;// 表示机器人坐标
s = input.next();
char a[] = s.toCharArray();
for (j = 0; j < s.length(); j++) {
if (a[j] == 'L')
L1++;
else if (a[j] == 'R')
R1++;
else if (a[j] == 'M') {//确定坐标及方向
sum = L1 - R1;
if (sum > 0) {// 表示向左转的次数多,并且抵消后按照左转的次数求出方向
if (sum % 4 == 0) {
direction = 'N';
y++;
}
else if (sum % 4 == 1) {
direction = 'W';
x--;
}
else if (sum % 4 == 2) {
direction = 'S';
y--;
}
else if (sum % 4 == 3) {
direction = 'E';
x++;
}
} else {
//sum = -sum;
if (sum % 4 == 0) {
direction = 'N';
y++;
}
else if (sum % 4 == 1) {
direction = 'E';
x++;
}
else if (sum % 4 == 2) {
direction = 'S';
y--;
}
else if (sum % 4 == 3) {
direction = 'W';
x--;
}
}//else
}//else if(a[j]=='M)
//System.out.println(sum);
}//for(j=0;j<s.length();j++)
System.out.println(x+" "+y+" "+direction);
}
}
}
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
int i, j;
String s;
char direction;
int x, y;// 表示机器人的坐标
for (i = 1; i <= t; i++) {// t组操作
s = input.next();
//s=input.nextLine();//WA
char a[] = s.toCharArray();
x = y = 0;// 机器人的初始坐标
direction = 'N';// 机器人的初始方向
for (j = 0; j < s.length(); j++) {
if (a[j] == 'L') {
if (direction == 'N')
direction = 'W';
else if (direction == 'W')
direction = 'S';
else if (direction == 'S')
direction = 'E';
else if (direction == 'E')
direction = 'N';
} else if (a[j] == 'R') {
if (direction == 'N')
direction = 'E';
else if (direction == 'E')
direction = 'S';
else if (direction == 'S')
direction = 'W';
else if (direction == 'W')
direction = 'N';
} else if (a[j] == 'M') {
if (direction == 'N')
y++;
else if (direction == 'W')
x--;
else if (direction == 'S')
y--;
else if (direction == 'E')
x++;
}
}
System.out.println(x + " " + y + " " + direction);
}
}
}