输入时这个:A10;S20;W10;D30;X;A1A;B10A11;;A10;
输出是:0,0
debug了下,m.find()的那个循环直接跳过了,不知道为什么啊,求大神帮助啊
下面是代码:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNextLine()){
String str=sc.nextLine();
int x=0;
int y=0;
Pattern p = Pattern.compile("^[ASDW][0-9]+$"+";");
Matcher m = p.matcher(str);
while(m.find()){
String s = m.group();
char ch=s.charAt(0);
s=s.substring(1, s.length()-1);
int n=Integer.parseInt(s);
switch(ch){
case 'A':
x-=n;
break;
case 'D':
x+=n;
break;
case 'S':
y-=n;
break;
case 'W':
y+=n;
break;
default:
break;
}
}
System.out.println(x+","+y);
}
}
}
输出是:0,0
debug了下,m.find()的那个循环直接跳过了,不知道为什么啊,求大神帮助啊
下面是代码:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNextLine()){
String str=sc.nextLine();
int x=0;
int y=0;
Pattern p = Pattern.compile("^[ASDW][0-9]+$"+";");
Matcher m = p.matcher(str);
while(m.find()){
String s = m.group();
char ch=s.charAt(0);
s=s.substring(1, s.length()-1);
int n=Integer.parseInt(s);
switch(ch){
case 'A':
x-=n;
break;
case 'D':
x+=n;
break;
case 'S':
y-=n;
break;
case 'W':
y+=n;
break;
default:
break;
}
}
System.out.println(x+","+y);
}
}
}
改成这样Pattern p = Pattern.compile("[ASDW][0-9]+;");
int x = 0;
int y = 0;
final Pattern p = Pattern.compile("([ASDW]\\d+)(?:;*)");
final Matcher m = p.matcher(str);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
final char ch = s.charAt(0);
s = s.replaceAll("\\D+", "");
final int n = Integer.parseInt(s);
switch (ch) {
case 'A':
x -= n;
break;
case 'D':
x += n;
break;
case 'S':
y -= n;
break;
case 'W':
y += n;
break;
default:
break;
}
}
System.out.println(x + "," + y);
A10
S20
W10
D30
A1
A11
A10
-2,-10
B10A11 怎么分开