[英]Read characters from console, ignoring whitespaces and new lines
我有一個很容易解決的問題,但不是這樣。我得到了一個游戲的輸入,你必須從控制台讀取。輸入命令有:UP(U)、DOWN(D)、LEFT( L), RIGHT(R) 作為一個完整的字符串出現,例如:“RURD”。 我必須將它們分解成字符。我這樣做是這樣做的:
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++;
}
輸入如下:
Pesho - 播放器 1(使用掃描儀從控制台設置)
Ivo - 播放器 2(使用掃描儀從控制台設置)
3 3 - 矩陣尺寸(使用掃描儀從控制台設置)
PRA - 矩陣的第一行(使用掃描儀從控制台設置)
BB - second -//-(使用掃描儀從控制台設置)
RCI - 第三 -//-(使用掃描儀從控制台設置)
LRRU - 方向(使用掃描儀從控制台設置)
RD - 指向 go 的第二行方向(使用掃描儀從控制台設置)
我希望掃描儀讀取“LRRURD”,而不僅僅是“LRRU”,然后掃描第二行,因為可能有 n 行輸入。基本上我想在從控制台讀取時刪除空格和新行,同時讀取多行(使新行連接到前一行。
幫助將不勝感激:)
嘗試 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
with out replaceAll method :- this is some text
with replaceAll method :- thisissometext
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.