[英]Read characters from console, ignoring whitespaces and new lines
I have a question which is pretty easy to solve, yet not so.I am given an input for a game in which you have to read form the console.There are input commands: UP(U), DOWN(D), LEFT(L), RIGHT(R) coming in as a whole string ex: "RURD".我有一个很容易解决的问题,但不是这样。我得到了一个游戏的输入,你必须从控制台读取。输入命令有:UP(U)、DOWN(D)、LEFT( L), RIGHT(R) 作为一个完整的字符串出现,例如:“RURD”。 I have to break them down into characters.I did it by doing this:我必须将它们分解成字符。我这样做是这样做的:
String ninja1Name = scanner.nextLine();
String ninja2Name = scanner.nextLine();
int[] arr = Arrays.stream(scanner.nextLine().split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
Ninja ninja1 = new Ninja(ninja1Name);
Ninja ninja2 = new Ninja(ninja2Name);
Field field = new Field(ninja1, ninja2);
field.createMatrix(arr[0], arr[1], scanner);
//U, D, L, R -> directions to move(last lines of the input which I'm talking about)
String tokens = scanner.nextLine();
char[] commands = tokens.toCharArray();
int currentCommandIndex = 0; // Initialization
boolean gameEnded = false;
while (!gameEnded) {
char currentCommand = commands[currentCommandIndex];
gameEnded = field.moveCurrentPlayer(currentCommand);
currentCommandIndex++;
}
the input is as follows:输入如下:
Pesho - player 1(set from console using scanner) Pesho - 播放器 1(使用扫描仪从控制台设置)
Ivo - player 2(set from console using scanner) Ivo - 播放器 2(使用扫描仪从控制台设置)
3 3 - matrix dimensions(set from console using scanner) 3 3 - 矩阵尺寸(使用扫描仪从控制台设置)
PRA - first row of matrix(set from console using scanner) PRA - 矩阵的第一行(使用扫描仪从控制台设置)
BB - second -//-(set from console using scanner) BB - second -//-(使用扫描仪从控制台设置)
RCI - third -//-(set from console using scanner) RCI - 第三 -//-(使用扫描仪从控制台设置)
LRRU - directions to go(set from console using scanner) LRRU - 方向(使用扫描仪从控制台设置)
RD - second line of directions to go (set from console using scanner) RD - 指向 go 的第二行方向(使用扫描仪从控制台设置)
I want the scanner to read "LRRURD", not only "LRRU", then scan the second line, because there might be n lines of input.Basically I want to remove the whitespaces and new lines when reading from console, whilst reading multiple lines(making the new line concatinate to the previous one.我希望扫描仪读取“LRRURD”,而不仅仅是“LRRU”,然后扫描第二行,因为可能有 n 行输入。基本上我想在从控制台读取时删除空格和新行,同时读取多行(使新行连接到前一行。
Help would be greatly appreciated:)帮助将不胜感激:)
try replaceAll method尝试 replaceAll 方法
public class Test {
public static void main(String[] args) {
String originalStr = "this is some text";
System.out.println("with out replaceAll method :- "+originalStr);
originalStr = originalStr.replaceAll("[\\n\\t ]", "");
System.out.println("with replaceAll method :- "+originalStr);
}
}
output output
with out replaceAll method :- this is some text
with replaceAll method :- thisissometext
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.